我正在尝试更新数组中的子文档books,但未成功。新数据将不会保存。

表达:

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


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


我究竟做错了什么?

编辑:

库表:

       {
        "_id": {
            "$oid": "12345"
        },
        "Name": "A random libary",
        "Books": [
            {
                "_id": {
                    "$oid": "1"
                }
                "title": "TitleExample",
                "Chapters": [
                    {
                      chapterTitle: "first chapter etc"
                    }]
            },
            {
                "_id": {
                    "$oid": "2"
                }
                "title": "Another book"  ,
                "Chapters": [
                    {
                      chapterTitle: "first chapter etc"
                    }]
             }
           ]
         }

最佳答案

I updated my answer.

router.put("/:id/:bookid", (req, res) => {
      Library.findOne({ _id: req.params.id, "books._id": req.params.bookid }).exec(function(err,result){
    if(err)throw err;
    if(result){
    result.books.title="new value";
    result.save()
    console.log("new value")
    }
    else{console.log("not found")}
    })
    });


您可以尝试一下,可能会对您有所帮助。

关于node.js - updateOne $ set不起作用- Mongoose ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49639306/

10-11 00:03