繁体   English   中英

无法更新 Mongoose 对象数组中的文档属性值

[英]Unable to update a document's property value which is in an array of objects in Mongoose

所以我正在开发这个需要更新文档的应用程序。 该文档包括一系列对象。 所以我需要更新其中一个对象的属性值,但在更新之前,我需要根据数组索引找到正确的 object。

async function updatePost (post) {

    const pendingPostIndex = post.postContent.findIndex( item => {
          return item.status === "pending";
    });

    const update = {
          pid: 0,
          postContent[pendingPostIndex].status: "completed"
    }

    await Post.findOneAndUpdate({ _id: post._id }, update);
}

当我必须更新特定帖子时,会调用上面的 function。 参数post是我必须更新的文档。

然后我正在寻找待处理的帖子的index ,以便我可以使用索引来更新待complete状态以及将pid值更新为 0。显然,像这样更新pid值是可行的。 但不是第二个。

上面的代码通过在上面的update object 中的第二个属性下面用红色下划线来显示 VS Code 中的错误。

终端显示SyntaxError: Unexpected token '['

数据如下所示:

{
     "pid" : 4927fn380m38jc5, 
     "postContent" : [ 
        {
            "status" : "pending",
            "text" : "post 1",
            "image" : ""
        }, 
        {
            "status" : "complete",
            "text" : "post 2",
            "image" : ""
        }, 
        {
            "status" : "pending",
            "text" : "post 3",
            "image" : ""
        }
    ],
}

首先,object 中的以下语法完全错误:

postContent[pendingPostIndex].status: "completed"

其次,如果您只想更新 pid 和 status 为什么不:

const update = {
          pid: 0,
          status: "completed"
}
await Post.findOneAndUpdate({ _id: post._id }, update);

根据评论编辑:

如果只想在状态待定的特定索引处更新数组内的子文档。 你只想:

const statusKeyUpdate = "postContent."+ pendingPostIndex +".status";

Post.findOneAndUpdate(
   { _id: post._id, "postContent.status": "pending" },
   { $set: { "pid":0, [statusKeyUpdate]:"completed" } }
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM