简体   繁体   中英

NodeJS MongoDB Projection not working

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

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

eg 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

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 
}

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