Home > Software engineering >  Mongoose find with some undefined fields
Mongoose find with some undefined fields

Time:08-05

I am trying to understand the behaviour of passing an object to findOne when some of the fields are undefined. Even stepping through the nodejs code I don't see it ever directly manipulate undefined fields, but it seems to.

Suppose I have a model like

_id: object id
relationA: object id
relationB: object id

If I do

mymodel.findOne({relationA: id, relationB: undefined})

It will not return results where it satisfies relationA: id. I thought it would just ignore relationB because it is undefined, but I can't tell what it does instead.

Does it

  1. Convert this to null?
  2. Convert this to {$exists: false}?
  3. Is it only special when it is an ObjectId

Thanks

CodePudding user response:

When passing an object with key/values to the findOne function, you are passing a query.
The mongoDb engine search for documents that are matching you query criteria, that is, documents where relationA equals to the value of id AND relationB is undefined (or Null, for that matter).
If you only want to match documents that have relationA equal to some value, remove the relationB part: mymodel.findOne({relationA: id}.

  • Related