【问题标题】:How can I update multiple fields in an array of embedded documents Mongoose?如何更新嵌入文档 Mongoose 数组中的多个字段?
【发布时间】:2020-02-07 02:40:20
【问题描述】:

我的猫鼬模型:

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

我希望在我的数据库中具有不同作者和标题的两个表单提交(POST)得到以下结果:

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

我不关心两个帖子中的 ISBN,因为它不是我们架构中的必填字段。由于我的books 子文档一开始是空的,所以我无法在我的代码中正确设置positional operator ($)。请帮我正确写findOneAndUpdate查询!

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

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

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

    【讨论】:

    • {$push: update} 其中update={'books.$.title' : req.body.title , 'books.$.author' : req.body.author} 不是一回事??
    • 不,不是,books.$.title 表示您在每个 book 项目中都有 title 数组。
    • 感谢您的帮助!
    猜你喜欢
    • 2020-06-07
    • 2020-02-07
    • 2014-06-12
    • 2023-03-10
    • 1970-01-01
    • 2019-02-01
    • 2016-10-06
    • 2022-01-02
    • 2020-11-19
    相关资源
    最近更新 更多