Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  });
};
like image 273
Rohan Sharma Avatar asked Feb 23 '15 08:02

Rohan Sharma


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I get MongoDB data from node JS?

To select data from a collection in MongoDB, we can use the findOne() method. The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object.


1 Answers

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

Data.find({}).project({ _id : 1, serialno : 1 }).toArray()
like image 78
lee shin Avatar answered Sep 29 '22 16:09

lee shin