skip to Main Content

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

4

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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
    }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search