findOne mongoose code example
Example 1: mongoose model
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
Example 2: findbyid mongoose
await Adventure.findById(id).exec();
Adventure.findById(id, function (err, adventure) {});
await Adventure.findById(id, 'name length').exec();
Example 3: mongodb findone
itemsCollection.findOne(query, projection)
.then(result => {
if(result) {
console.log(`Successfully found document: ${result}.`);
} else {
console.log("No document matches the provided query.");
}
return result;
})
.catch(err => console.error(`Failed to find document: ${err}`));
Example 4: 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 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: mongoose find
const query = Customer.find().sort({ name: 1 }).limit(1);
query.getOptions();