简体   繁体   English

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

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

So I am working on this app where I need to update a document.所以我正在开发这个需要更新文档的应用程序。 The document consists an array of objects among other things.该文档包括一系列对象。 So I need to update a property value in one of those objects but before updating I need to find the correct object based on array index.所以我需要更新其中一个对象的属性值,但在更新之前,我需要根据数组索引找到正确的 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);
}

The function above is called when I have to update a specific post.当我必须更新特定帖子时,会调用上面的 function。 The parameter post is the document I will have to update.参数post是我必须更新的文档。

Then I'm looking for the index of the post which is pending so that I can use the index to update the pending status to complete as well as the pid value to 0. Obviously, updating the pid value like this works.然后我正在寻找待处理的帖子的index ,以便我可以使用索引来更新待complete状态以及将pid值更新为 0。显然,像这样更新pid值是可行的。 But not the second one.但不是第二个。

The above code shows error in VS Code by underlining it red below the second property in the update object above.上面的代码通过在上面的update object 中的第二个属性下面用红色下划线来显示 VS Code 中的错误。

The terminal says SyntaxError: Unexpected token '['终端显示SyntaxError: Unexpected token '['

The data looks like this:数据如下所示:

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

Firstly following syntax is totally wrong inside object:首先,object 中的以下语法完全错误:

postContent[pendingPostIndex].status: "completed"

Secondly if you just want to update pid and status why not:其次,如果您只想更新 pid 和 status 为什么不:

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

EDIT based on comment:根据评论编辑:

If just want to update subdocument inside array at specific index where status is pending.如果只想在状态待定的特定索引处更新数组内的子文档。 You just want:你只想:

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