1

I noticed a case where (accidentally) the value passed into Model.findOne was a key that is not defined in schema. I expected an error or undefined but what is happening is that for exampe when I search for a user, if the value i pass in is undefined ANY random (as it seems) and wrong user is returned.

//if I would pass in instead of:

function (req, res, next) {
  const email = req.body.email
  User.findOne({email: email})
}

this:

function (req, res, next) {
  const email = req.body.email
  User.findOne({emaill: email})
}

then, because 'emaill' does not exist in the schema, instead of an err, I would get another user returned.

Could someone explain to me why this happens and how I can handle it. I cant handle error and check if passed value doesnt exist in schema..

  • Try increasing the log verbosity of your mongod server so you can see the query passed in. Does the query send to the database even contain the field that doesn't exists in the model? – Joe Jan 01 '23 at 20:15
  • 2
    https://mongoosejs.com/docs/guide.html#strictQuery – user20042973 Jan 01 '23 at 20:22
  • thank you user20042973, that helps a lot! –  Jan 01 '23 at 20:50

0 Answers0