'excluding some data while retrieving data from mongodb is not working
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 }
);
Solution 1:[1]
You should use projection like this:
var cursor = client
.db('so')
.collection('sample')
.find()
.project({ _id: 0, messages: 0 });
await cursor.forEach(console.dir);
// { lastMessage: { content: "Hey, how's it?", sender: 'urtheaman' } }
You can see the full sample runnable file here.
Also, I would suggest that you should use mongoose instead of mongo driver for node for a better development experience.
Solution 2:[2]
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.
Solution 3:[3]
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
}
Solution 4:[4]
documentation says
You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field
// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }
// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }
i'm only withholding at a time, not doin both but still doesn't work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devesh |
| Solution 2 | Chinmay Aggarwal |
| Solution 3 | |
| Solution 4 | theaman |
