Mongoose FindOneAndUpdate 嵌入对象并返回父对象 [英] Mongoose FindOneAndUpdate an embedded object and return parent

查看:36
本文介绍了Mongoose FindOneAndUpdate 嵌入对象并返回父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 这个问题,但我在另一个方面遇到了困难.我的 mongo 数据库中的文档中嵌入了一组对象/子文档,架构如下....

I'm having a similar problem laid out in this question, but I'm stumbling on a different aspect. I have an array of objects/subdocuments embedded within a document in my mongo database, schema like this....

const projectSchema = new mongoose.Schema({
   name: {
      type: String
   },
  ...
   stakeholders: [{
    stakeholderTitle: {
        type: String,
        max: 150,
        required: [true, 'A stakeholder must have a title.']
        },
        ...
    }],

我需要做的是根据查询更新特定的嵌入对象,但我仍然需要返回父文档.根据对这个问题的回答,我能够使用id检索父文档子文档,但是当我尝试更新子文档时,我无法弄清楚.这是我的查询

what I need to do is update a particular embedded object based on the query, but I still need to then return the parent document. Based on an answer to this question, I was able to retrieve the parent document using the id for the subdocument, but when I then try and update the subdocument, I can't figure it out. This is my query

const filter = { 'stakeholders._id': req.body.stakeholderId }
const update = { stakeholderTitle: req.body.stakeholderTitle } // suspect the problem is here

let project = await Project.findOneAndUpdate(filter, update, {
    new: true,
    runValidators: true
})

这会按预期获取父文档,并且我假设我的更新"参数是问题所在,但是当我的查询已经基于 id 进行查找"时,我不完全确定如何更新我想要,但不是更新".

This fetches the parent document as intended, and I'm assuming that my 'update' argument is where the problem is, but I'm not entirely sure how to update when my query is already 'finding' based on the id I want, but not 'updating'.

推荐答案

您的 update 语句要求 stakeholderTitle 位于文档的根级别.要正确定义路径,您必须使用 $ 位置运算符:

Your update statement expects stakeholderTitle to be on a root level of your document. To define the path correctly you have to use the $ positional operator:

const update = { 'stakeholders.$.stakeholderTitle': req.body.stakeholderTitle }

这篇关于Mongoose FindOneAndUpdate 嵌入对象并返回父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆