mongoose find by id code example
Example 1: mongo console find by id
db.collection.find({_id:ObjectId('5e208c18d598b806c869ca37')}).pretty()
Example 2: find one with specofoc id mongoose
YOUR_MODEL_NAME.findOne({_id: reqParameterID}, function(err, result) {
if (err) {
console.log(err);
} else {
}
});
Example 3: mongoose response to object
MyModel.findOne().lean().exec(function(err, doc) {
doc.addedProperty = 'foobar';
res.json(doc);
});
Example 4: findbyid mongoose
await Adventure.findById(id).exec();
Adventure.findById(id, function (err, adventure) {});
await Adventure.findById(id, 'name length').exec();
Example 5: mongoose where
exports.generateList = function (req, res) {
subcategories
.find({})
.where('categoryId').ne([])
.populate('categoryId')
.where('active').equals(true)
.where('display').equals(true)
.where('categoryId.active').equals(true)
.where('display').in('categoryId').equals(true)
.exec(function (err, data) {
if (err) {
console.log(err);
console.log('error returned');
res.send(500, { error: 'Failed insert' });
}
if (!data) {
res.send(403, { error: 'Authentication Failed' });
}
res.send(200, data);
console.log('success generate List');
});
};
Example 6: callback mongoose get value from document
var query = Model.find({});
query.where('field', 5);
query.limit(5);
query.skip(100);
query.exec(function (err, docs) {
});