'Query specific fields of mongoDB using node.js

In the code below the query gives me all the fields. I only want to query _id and serialno. How to go about it.

Schema

var DataSchema = new Schema({
  serialno: String,
  info: String,
  active: Boolean,
  content: String
});

Query

// Get list of datas
exports.index = function(req, res) {
  Data.find(function (err, data) {
    if(err) { return handleError(res, err); }
    return res.json(200, data);
  });
};


Solution 1:[1]

If you are using latest nodejs mongodb driver 3.0 or above try this code:

Data.find({}).project({ _id : 1, serialno : 1 }).toArray()

Solution 2:[2]

To query and return only specific fields, this is the correct request :

Data.find({}, { _id : 1, serialno : 1 }, function (err, data) {
  if(err) { return handleError(res, err); }
  return res.json(200, data);
});

The second object params is the projection params, in this object, you can set fields to return or hide.

More informations here : http://docs.mongodb.org/manual/reference/method/db.collection.find/

Solution 3:[3]

In MongoDB Node.js Driver v3.1 and above:

Collection.find({}, {
   projection: {
     _id: false,
     someField: true
   }
});

Second argument to the find/findOne function is options. It supports limit, sort, projection, and many more filters.

Source: http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOne

Solution 4:[4]

Following the documentation, you are using the function collection.find(query[[[, fields], options], callback]);

So you need to specify the fields argument:

Data.find(null, { "_id": true, "serialno": true }, function (err, data) {
    if(err) { return handleError(res, err); }
    return res.json(200, data);
  });

Solution 5:[5]

You can use Below code

enter code here`collection.find({}, { projection: {_id:1, serialno: 1}}

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 lee shin
Solution 2 throrin19
Solution 3 Nishant Ghodke
Solution 4 alandarev
Solution 5 Khader M A