问题
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