Mikheil
Mikheil

Reputation: 39

Update a document in an array and return the document in mongoDB

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?

Upvotes: 0

Views: 57

Answers (1)

Muhammed Shafi S R
Muhammed Shafi S R

Reputation: 94

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

Upvotes: 1

Related Questions