Query specific fields of mongoDB using node.js

青春壹個敷衍的年華 提交于 2020-12-09 04:25:15

问题


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

回答1:


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

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



回答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/




回答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




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


来源:https://stackoverflow.com/questions/28669849/query-specific-fields-of-mongodb-using-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!