简体   繁体   中英

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:

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 });
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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