Mongoose findOneAndUpdate返回invalidate错误

时间:2015-10-29 11:51:26

标签: node.js mongodb mongoose upsert

我试图为此计划添加评论:

var CommentSchema = new Schema(
{
    ad_id:String,
    comments:
    [
        {
            author: String,
            authorID: Number,
            posted: Date,
            text: String,
            title: String
        }  
    ]
}

但如果ad_id存在,我只想将新评论推送到comments基本上创建upsert查询:

var query = {'ad_id': req.body.data.ad_ID}
    var doc = {$set:{'ad_id':req.body.data.ad_ID},$push:{'comments':{'author':req.body.data.author,'authorID':req.body.data.uID,'posted':req.body.data.posted
    ,'text':req.body.data.text, 'title':req.body.data.title}}};
    var options = {upsert:true};

    Comments.findOneAndUpdate(query,doc,options, function (err, doc) {
        if(err) {
            console.log(String(err));
            res.send({"foo": String(err)});
        }
        else {
            console.log((doc));
            res.send(doc);
        }
    });

但是得到了以下错误:

Unable to invalidate a subdocument that has not been added to an array.

1 个答案:

答案 0 :(得分:0)

事实证明,我遇到了数据类型错误。 如果有人遇到错误代码,请确保data types与输入匹配。