2

I made a findOneAndUpdate on NodeJS with the following Code

var themessageid = "ID of message A"
workstreamchat.findOneAndUpdate(
    { 'chat.sidmessage': themessageid }, 
    { '$set': { 
        'chat.$.linkinfo': linkinfo 
    } }, 
    { returnOriginal: false }, 
    function(err, res) {
        console.log(res);            
    }
);

e.g of document returned

{
    "_id": "mongoid",
    "chat": [
        {
            "sidmessage": "id_of_message_A",
            "usersid": "38jrc05h14avm14e",
            "messageinfo": {
                "text": "Message A"
            }, 
            "linkinfo": "something" 
        },
        {
            "sidmessage": "id_of_message_B",
            "usersid": "38jrc05h14avm14e",
            "messageinfo": {
                "text": "MessageB"
            }
        }
    ]
}

It works flawlessly and returns the updated document with the updated specific object in the whole array.

The problem is I wanted to use projection to return the chat array only with the updated document. I have tried

{ projection: { 'chat.$': 1 }, returnOriginal: false }

and

{ projection: { chat: chat.$ }, returnOriginal: false }

But everytime this kind of projection with returnOriginal returns null.

e.g of expected document

{
    "_id": "mongoid", 
    "chat": [
        {
            "sidmessage": "id_of_message_A",
            "usersid": "38jrc05h14avm14e",
            "messageinfo": {
                "text": "Message A"
            },
            "linkinfo": "something"
        }
    ],
}

Notes:

The documentation I am using.

My npm version is 6.4.0

My MongoDB driver version is 3.1.4

1

1 Answer 1

1

I managed to find the answer after testing multiple cases.

What i needed was.

{
     projection: { 
          chat: { 
              $elemMatch: { sidmessage: new ObjectId(id_of_message_A) } 
          }
     }, 
     returnOriginal: false 
}
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.