Alexander Zeitler
Alexander Zeitler

Reputation: 13099

Force mongoose to throw if find param is not an object

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

Answers (2)

Manjeet Singh
Manjeet Singh

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

Raunik Singh
Raunik Singh

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

Related Questions