How to Set “OR”, “AND”, “SORT”, “LIMIT” Operator in Mongoose + MongoDB
Mongoose is Object – Database modeling library with mongodb and node.js.
Contents
How to set “OR" and “AND" query in find methods?
You can set “OR" operator in the find method like the following syntax.
$or: [{condition1},{condition2}]
Example 1. Use “$or" operator.
pets = await Pet.find({
$or: [
{ email: user.email },
{ ownerId: authUserId },
],
});
Example 2. Use “$or" and “$and" operator.
pets = await Pet.findOne({
$and: [
{
$or: [
{ email: user.email },
{ ownerId: authUserId },
],
},
{ _id: petId },
],
});
How to Use “SORT" and “LIMIT"
Example 3. Use “sort()" and “limit()“
feds = await Feed.find({ petId: 'PETID' }).sort({ date: -1 }).limit(5);
Delete Array Elements in Document with Mongoose
To use “$pull" or “$pullAll" is recommended.
Example 4. Use $pullAll
await User.updateOne({ authUserId: 'user001' },{ $pullAll: { pets: [petId] } });
Discussion
New Comments
No comments yet. Be the first one!