Home > Back-end >  excluding some data while retrieving data from mongodb is not working
excluding some data while retrieving data from mongodb is not working

Time:05-10

i'm using mongodb nodejs driver.

const res = await chats.findOne({ _id: chatId }, { messages: 0, _id: 0 });

this is what i'm getting in response, i don't wanna get messages and _id property on received data

{
      "_id": "d0fff742-4af5-4e6a-bd51-9aa47da08fb9",
      "messages": "ea678ca7-81fb-479b-89f8-7995d8831992",
      "lastMessage": {
        "content": "Hey, how's it?",
        "sender": "urtheaman"
      }
    }
  }

collection.find(query, options) $slice isn't working as well. i think entire options parameter isn't working.

const res = await messages.findOne(
      { _id: messagesId },
      { messages: { $slice: [from, 15] }, _id: 0 }
    );

CodePudding user response:

Try using:

const res = await chats.findOne({ _id: chatId }, { messages: 1, _id: 1 });

If you want to have a field, make sure it's one else 0.

CodePudding user response:

You are supposed to get the whole document back and then have a function of your own that handles that data in a way that is useful to you.

You could do

function getLastMEssage (data){
    return data.lastMessage.content
}
  • Related