user3479683 user3479683 - 5 months ago 23
Node.js Question

How to only include specific fields when returning all documents from a collection

I am using NodeJS and MongoDB. I am trying to query my DB and return all documents from a collection, but I'm also trying to limit which fields get returned. I am having trouble, here is my code. Can someone point out what I am doing wrong?

collection.find(
{ type: 1 },
{'_id': 0, 'firstName': 1, 'lastName': 1, 'email': 1, 'zip': 1}, function(err, allUsersObject) {

return res.send({data: allUsersObject, status: 200});
});

Answer

You're missing '{fields: }'. I fixed your query for you, see below:

collection.find(
      { type: 1 }, 
      {fields: 
        {'_id': 0, 'firstName': 1, 'lastName': 1, 'email': 1, 'zip': 1}
      }, function(err, allUsersObject) {

      return res.send({data: allUsersObject, status: 200});
    });