简体   繁体   English

猫鼬。 按文档ID更新引发[TypeError:无法读取未定义的属性'_id']

[英]Mongoose. Update by document id throws [TypeError: Cannot read property '_id' of undefined]

There is my code: 有我的代码:

    var fileModel = context.models.File,
                query = {
                    _id: context.models.ObjectId("532083358ab1654c0c8b4ced") // TODO: for debug, change after update fix
                },
                update = {
                    description: context.data.description,
                    userId: context.data.userId ?
                        context.models.ObjectId(context.data.userId) : undefined,
                    isAdded: true
                };
            fileModel.update(query, update, { multi: true }, function (err) {
                if (err) {
                    console.log('update');
                    console.log(err);
                    context.sendJson({ success: false, err: err });
                }
                else {
                    context.sendJson({ success: true });
                }
            });

There is my Schema: 有我的架构:

var fileSchema = new schema({
        path:  { type: String, required: true, validate: [validateName, 'a path is required'] },
        isApproved:  { type: Boolean, default: false },
        isAdded:  { type: Boolean, default: false },
        name:  { type: String, required: true, validate: [validateName, 'a name is required'] },
        description: { type: String },
        userId: { type: schema.Types.ObjectId },
        updated: { type: Date, default: Date.now },
        size: { type: Number }
    }, { autoIndex: false });

When I try to update document by id I see this messages in console: 当我尝试通过ID更新文档时,我在控制台中看到以下消息:

update
[TypeError: Cannot read property '_id' of undefined]

I think problem in 我认为有问题

userId: context.data.userId ?
    context.models.ObjectId(context.data.userId) : undefined,

But I don't understand how fix it. 但我不知道如何解决。

I solve this by separate part of my code. 我通过代码的单独部分解决了这个问题。 But I can't understand what's wrong in my first solution. 但是我不明白我的第一个解决方案出了什么问题。 That's working code: 那是工作代码:

var fileModel = context.models.File,
        query = {
            _id: {
                $in: context.data.files.map(function (el) {
                    return context.models.ObjectId(el);
                })
            }
        },
        update = {
            description: context.data.description,
            isAdded: true
        };
    if (context.data.userId){
        update.userId = context.models.ObjectId(context.data.userId);
    }
    fileModel.update(query, update, { multi: true }, function (err) {
        if (err) {
            console.log('update');
            console.log(err);
            context.sendJson({ success: false, err: err });
        }
        else {
            context.sendJson({ success: true });
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM