I'm having a collection in my database called businesses. What I want to do is query the database and specific fields, defined in my schema, and not all the fields of the document. I thought that's the reason why the schema exists in the first place ?
Schema
var businessSchema = new mongoose.Schema({
custom_id: String,
name: String
});
module.exports = mongoose.model('Business', businessSchema);
Express
router.get('/query', function (req, res, next) {
res.type('json');
Business.find({custom_id: req.query.custom_id})
.then(function (data) {
res.send({data: data});
}).catch(function (err) {
return next(new Error(err.message || err));
})
});
Response
{
"data":[
{
"_id":"5a50ac105a0d8452b0e341e5",
"custom_id":"1",
"name":"Dave and Jane",
"status":"active",
"verified":true,
"created":1492727550760,
"email":{
"address":"dave_jane@whatever.com"
}
}
]
}
In the schema I have only custom_id and name, but whatever fields I define (or I don't), all the fields of the documents are returned when Business.find
executes.
Same behavior as if the schema was empty, thus, returning all fields.
In the select function just set the fields you want as 1 and the ones you don't want as 0. See below:
router.get('/query', function (req, res, next) {
res.type('json');
Business.find({custom_id: req.query.custom_id}).select({ "name": 1, "_id": 0})
.then(function (data) {
res.send({data: data});
}).catch(function (err) {
return next(new Error(err.message || err));
})
});