Search code examples
javascriptnode.jsmongodbmongoosesubdocument

Find Documents whose Subdocument Fields partially match given Criteria with Mongoose


I have using nodeJS and mongoose/mongoDB to build an API. Consider the following model for a generic Model (Gmodel):

{
   name: "teleni",
   type: "person",
   data: mixed
}

The data field in this document is a mixed type so it can be anything, but I intend for it to be a subdocument/object in most cases (depending on the value of the type field). If I wanted to find all the documents that were of type person I would execute the following code:

Gmodel.find({type: "person"}, callbackFunction)

Now consider another instance of the Model:

{
   name: "teleni",
   type: "person",
   data: {
      data_type: "event",
      date: "Jan 30 2019"
   }
}

My issue is that I want to use mongoose to find all documents where the data field is an object/document where the data_type field is "event". I have tried the following code:

Gmodel.find({data: {data_type: "event"}}, callbackFunction)

However nothing is returned when I execute this code because find is looking for Documents where the data field is exactly {data_type: "event"}. So how do I use find to retrieve Documents whose subdocuments (of mixed type) partially match a criteria, similar to how find works on top level fields.


Solution

  • You can use the dot syntax data.data_type to specify a field in subdocument. This way it would match on the basis on this field only, not the entire subdocument as in your original code.

    Gmodel.find({data.data_type: "event"}, callbackFunction)