Mongoose findone returns wrong user when the field passed in, is not defined in schema. How can I handle this case?

54 Views Asked by At

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..

0

There are 0 best solutions below