如何更新嵌入式文档Mongoose数组中的多个字段?

时间:2019-10-09 17:44:47

标签: mongodb mongoose mongodb-query mongoose-schema

我的猫鼬模型:

const userSchema = Schema({
  firstName: String,
  lastName: String,
  books: [{title: String, author: String, isbn: Number}]
});

我想为每个POST请求添加a new title & author with a book object。我目前给我positional operator did not find the match错误的方法:

var User = mongoose.model("User", userSchema);
router.post('/submit', (req, res) => {    
    let update={
              'books.$.title' : req.body.title,
              'books.$.author' : req.body.author
               }
    User.findOneAndUpdate({_id:req.body.user_id},{$push: update},{new: true}).exec(function(err, doc) {
      if (err){
        console.log(err);
        return;
      }
     res.send(doc);
    });
});

对于我的数据库中具有不同作者和标题的两种形式的Submit(POST),我希望获得以下结果:

{
  _id: 'SomeId'
  firstName: 'John',
  lastName: 'Cena',
  books: [{title: 'a', author:'b' }, {{title: 'c', author:'d' }}]
}

我都不在乎这两篇文章中的ISBN,因为在我们的架构中它不是必填字段。由于我的books子文档开始时为空,因此我无法在代码中正确设置positional operator ($)。请帮助我正确编写findOneAndUpdate查询!

1 个答案:

答案 0 :(得分:1)

$push需要字段名称和值,在您的情况下,字段名称为book,值是对象{author, title}

User.findOneAndUpdate({_id:req.user._id}, {$push : { books : { author: "c", title: "d"}}})