node.js - updateOne $set 函数在 Mongoose 中不起作用

标签 node.js express mongoose

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

express :

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

库场景:

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

书场景:

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"
        }]  
    }]
}

最佳答案

你可以试试这个:

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/

相关文章:

javascript - 用传递的结果重构 promise 级联

javascript - 返回 Mongodb 查询 Distinct

javascript - 在推送到数组时更新插入文档

javascript - 在express js中制作api时出现 "cannot get"错误

node.js - yarn 错误 "EACCESS: permission denied, scandir '/home/ubuntu/.config/yarn/link'"

javascript - Visual Studio 代码 IntelliSense 不适用于 NodeJS

node.js - 使用 Node js、express和mongodb在点击位置时在谷歌地图上显示用户信息

node.js - 如何在 NodeJS 中使用多部分表单数据时访问正文参数

node.js - 带有 mongoose node.js 的时间序列文档?

node.js - Redis 服务重启时出现 Redis 错误 "NOSCRIPT No matching script. Please use EVAL"