0

So I have an only array in a collection, which has a name of "posts". I am trying to update a document in that array and return the updated document. I tried this:

 Posts.updateOne(
            {},
            {
                $set : {
                    'posts.$[id].image' : cloudinaryUrl,
                    'posts.$[id].post' : req.body.updatedPost
                }
            },
            {
                arrayFilters: [
                    { 'id._id': new ObjectId(req.body.postID) },
                ],
            },
        ); 

I'm getting this:

{
    "data": {
        "acknowledged": true,
        "modifiedCount": 1,
        "upsertedId": null,
        "upsertedCount": 0,
        "matchedCount": 1
    }
}

And also this:

Posts.findOneAndUpdate(
            {
                'posts': {
                    $elemMatch: {
                        creatorId: req.userData.userId, 
                        _id: new ObjectId(req.body.postID),
                    }
                }
            },
            {
                $set : {
                    'posts.$.image' : cloudinaryUrl,
                    'posts.$.post' : req.body.updatedPost
                }
            },
        )

And I'm getting the whole collection (I'm just showing you 1 post):

{
    "data": {
        "_id": "63ddd8059b4324f25f69469e",
        "__v": 0,
        "posts": [
            {
                "post": "h123jjkkl",
                "image": "",
                "comments": [],
                "likes": 0,
                "creatorId": "63cdb85f5f2fb46f75781f7e",
                "date": "2023-02-04T04:36:31.982Z",
                "_id": "63dde0cf749dde1d574c29cf"
            },
]

But I can't get the updated document. Can someone help me do it?

1
  • 3
    What is it doesn't work? Show us some sample documents and expected output so we can take a closer look. Commented Feb 4, 2023 at 17:31

1 Answer 1

1
const updatedData = await User.findOneAndUpdate(
      { _id: userId },
      { $set: { 'posts.$[id].image' : cloudinaryUrl,
                    'posts.$[id].post' : req.body.updatedPost } },
      { returnDocument: "after" }
    );

You will get the updated document, you can use a async function or can get the data using .then and avoid the await keyword

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.