【问题标题】:updateOne $set function won't work in MongooseupdateOne $set 函数在 Mongoose 中不起作用
【发布时间】:2021-01-03 09:53:10
【问题描述】:

我正在尝试更新数组中的子文档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"
        }]  
    }]
}

【问题讨论】:

  • 您能否使用您尝试更新的文档以及req.params.idreq.params.bookid 的值更新您的问题?
  • @JohnnyHK 用文档更新了答案,勾选“编辑”
  • 您实际上并没有执行更新;查看链接的骗局。
  • @JohnnyHK 加.exec();就够了吗?还是有问题。

标签: node.js express mongoose


【解决方案1】:

你可以试试这个:

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

【讨论】:

  • 检查终端没有错误。还是我必须添加一些东西来检查是否有错误?
  • 没用,我认为问题是标题仍然是数组。我检查了console.log(result.books);,标题在result.books之后的数组中,这使得目标无法到达?当我使用result.books.title 时,我得到了undefinederror。你明白我的意思吗?
  • 什么是 $oid 我在你的架构中看不到
  • 我可以将书名更改为:result.books = [{ title: 'new value' }];,但该数组中的所有其他内容都会被删除。这是假设这样做还是我做错了?
  • $oid 由 mongoose 在创建新行时自动生成。我只需要使用_id 来比较它的值。
猜你喜欢
  • 2020-12-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多