本文介绍了Mongoose findOneAndUpdate 嵌套文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新包含 2 个其他文档的文档.为了完成这个任务,我使用了 findOneAndUpdate,但是 mongoose 向我抛出了一个 CastError(Cast to ObjectId failed).

I'm trying to update a document which contains 2 other documents. To achieve this task, I use findOneAndUpdate, but mongoose throws me a CastError (Cast to ObjectId failed).

我的模型:

user.js

var userSchema = new Schema({
    email: String,
    info: {
        type : Schema.ObjectId,
        required : true,
        ref : 'Info'
    }
});
module.exports = mongoose.model('User', userSchema);

info.js

var infoSchema = new Schema({
    firstname: String,
    lastname: String
});
module.exports = mongoose.model('Info', infoSchema);

我的查询:

var tmp = {
    email: req.body.email,
    info: {
        name: req.body.info.name
    }
};

User.findOneAndUpdate({
    _id: req.params.id
}, tmp, {
    upsert: false,
    new: true
}).exec(function(err, doc) {
    /* check errors */
    /* send response */
});

我做错了什么?我的模型设置不当吗?

What am I doing wrong? Are my models poorly set?

推荐答案

info的类型是Schema.ObjectId,而一个对象

info: {
    name: req.body.info.name
}

作为ObjectId传入,结果失败.

这也许是一种解决方法.

Here maybe one work around.

var new_info = new Info({
    firstname: req.body.info.name.firstname, //
    lastname: req.body.info.name.lastname    //
});

new_info.save(function(err, doc) {
    if (err)
        console.log(err);
    else {
        var tmp = {
            email: req.body.email,
            info: doc._id
        }

        User.findOneAndUpdate({
            _id: req.params.id
        }, tmp, {
            upsert: false,
            new: true
        }).exec(function(err, doc) {
            //
        });
    }
});

这篇关于Mongoose findOneAndUpdate 嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:59