【问题标题】:How to update embedded arrays/objects in MongoDb with mongoose?如何使用 mongoose 更新 MongoDb 中的嵌入式数组/对象?
【发布时间】:2020-03-19 20:49:43
【问题描述】:

我的 MongoDB 文档如下所示:

  {_id: ObjectId("xxx"),  
   username: 'user',  
   active_courses: [  
        {'name': 'MongoDB',  
         'notes': [  
           {'title': 'Note title',  
            'note': 'Actual note content'}  
       ]}  
    ]  

现在我需要更新带有标题“注释标题”的注释对象。我该怎么做?

我尝试了以下方法,但它不起作用。

Student.findOneAndUpdate(
		{username:req.body.username},
		{$set: {'active_courses.$[course].notes.$[note]': req.body}},
		{arrayFilters: [{'course.name': req.body.course},{'note.title': req.body.title} ]})
	.then(result => {
		res.status(200).json({message: 'Note saved!'})
	})

顺便说一句,我不知道数组的索引,所以我不能使用 active_courses[0].notes...

感谢有关此问题的任何帮助。谢谢!

【问题讨论】:

    标签: node.js mongodb mongoose document


    【解决方案1】:

    您可以将嵌入的文档定义为模式,这样 mongoose 会自动为它们生成一个 objectid。使用该 ID,您可以通过其父级访问并修改您的子文档,如下所示:

    var doc = parent.children.id(_id);
    

    Mongoose subdocuments

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 2023-01-18
      • 2020-10-01
      • 2021-06-17
      • 2015-12-12
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      相关资源
      最近更新 更多