mongoose find one code example
Example 1: mongoose find() example
await MyModel.find({});
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
await MyModel.find({ name: /john/i }, 'name friends').exec();
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Example 2: findbyid mongoose
await Adventure.findById(id).exec();
Adventure.findById(id, function (err, adventure) {});
await Adventure.findById(id, 'name length').exec();
Example 3: mongoose select
query.select('a b');
query.select(['a', 'b']);
query.select({ a: 1, b: 1 });
query.select('-c -d');
const schema = new Schema({
foo: { type: String, select: false },
bar: String
});
query.select('+foo');
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });
Example 4: 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');
});
};