javascript – Mongoose嵌入式文档更新

前端之家收集整理的这篇文章主要介绍了javascript – Mongoose嵌入式文档更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有嵌入式文档更新的问题.

我定义的方案:

var Talk = new Schema({
      title:{type: String,required: true},content: {type: String,date: { type: Date,comments: { type: [Comments],required: false},vote: { type: [VoteOptions],});

   var VoteOptions = new Schema({
    option: {type: String,required: true },count: {type: Number,required: false }
   });

现在我想更新vote.count,给定的Talk ID和VoteOption id.我有以下功能来完成这项工作:

function makeVote(req,res){

    Talk.findOne(req.params.id,function(err,talk) {
        for (var i=0; i <talk.vote.length; i++){
           if (talk.vote[i]._id == req.body.vote){
                talk.vote[i].count++;

           }
        }
              talk.save(function(err){
              if (err) {
                req.flash('error','Error: ' + err);
                    res.send('false');
               }
               else
               {
                    res.send('true');
               }
                 });
      });
}

一切执行,我得到res.send(‘true’),但是count的值不会改变.

当我做了一些console.log我看到它改变了价值,但talk.save不保存在db.

另外我很不高兴的循环只是找到_id的嵌入式文档.在mongoose文档中,我阅读了关于talk.vote.id(my_id),但这给我没有id功能错误.

解决方法

当更新混合类型(这似乎不是基本类型,也包括嵌入式文档)时,必须在文档上调用.markModified.在这种情况下,它将是:
talk.markModified("vote"); // mention that `talk.vote` has been modified

talk.save(function(err) {
    // ...
});

希望这能帮助未来的人,因为我找不到答案很快.

Reference:

… Mongoose loses the ability to auto detect/save those changes. To “tell” Mongoose that the value of a Mixed type has changed,call the .markModified(path) method of the document passing the path to the Mixed type you just changed.

原文链接:https://www.f2er.com/js/151467.html

猜你在找的JavaScript相关文章