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);
});
};
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
If you are using latest nodejs mongodb driver 3.0 or above try this code:
Data.find({}).project({ _id : 1, serialno : 1 }).toArray()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With