Reputation: 13099
Is there a way to force mongoose
to throw an error if the conditions
for a find
query is not an Object
but a Number
or String
?
Upvotes: 1
Views: 24
Reputation: 2398
You can use mongoose pre hook for this case
Model.pre('find', function () {
if (typeof(this.getQuery()) !== "object") {
next();
} else {
next(new Error('Your error message'))
}
});
Upvotes: 0
Reputation: 224
Its better to check all condition and validate the request params. Forcing mongo db to throw error not good practice. Mongo queries excepts object
let queryCondition = {};
queryCondition._id = "mongoDbId"
queryCondition.name = "anyName"
if(typeof(queryCondition) !== "object") return false
Model.find(queryCondition).lean();
Upvotes: 1