如何更新数组中的子文档 - mongoose

时间:2018-04-03 17:13:29

标签: javascript node.js express mongoose

我无法更新数组中的子文档。我现在可以只更新父文档。

我可以更新父文档的代码:

router.put('/:id/:bookid', (req, res) => {
  Library.findOne({
    _id: req.params.id //parent-id
  })
    .then(library => {

      //Update with new value
      library.Name = req.body.newName;

      library.save()
        .then(library => {
           //unrelated code
        })
    });
});

LibraryScema:

const LibarySchema = new Library({
  Name: {
    type: String,
    required: false
  }, 
  books: [BookSchema]
});

bookScema:

const BookSchema = new Schema({

  title: {
    type: String,
    required: false
  },
  Chapters: [
    {
      chapterTitle: {
        type: String,
        required: false
      }
    }
  ]
});

我的目的只是更新子文档,而不是同时更新父文档和子文档。

编辑:

早先的尝试:

router.put("/:id/:bookid", (req, res) => {
  Library.updateOne(
    { _id: req.params.id, "books._id": req.params.bookid },
    { $set: { "books.$.title": "New value" } }
  );
});

更改未保存,没有错误消息。

0 个答案:

没有答案
相关问题