简体   繁体   中英

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.

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. The parameter post is the document I will have to update.

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. 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.

The terminal says 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:

postContent[pendingPostIndex].status: "completed"

Secondly if you just want to update pid and status why not:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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