MongoDB and Mongoose | Nested Schema

I have two schemas, one of which is nested within the other. For the sake of the example:

const firstSchema = {
  name: String
}

const secondSchema = {
  example: [firstSchema],
  count: Number
}

const First = mongoose.model('First', firstSchema)
const Second = mongoose.model('Second', secondSchema)

Is there a way to do the following?

I want to find one specific secondSchema (let’s say using the find method) and then:
Within that secondSchema, I want to find a specific firstSchema, without looping
through the array, but instead again using something like find.

Thanks for your help

Hey there,

It sounds like $elemMatch might be helpful here. I’ll link the relevant section of the Mongoose docs: Mongoose v5.11.15: API docs

1 Like

Thanks! I’m struggling a bit with the syntax atm, just to dumb it down to my example, would it be something like this?

Second.findOne({count: 3}, (err, data) => {
  data.elemMatch('example', ({name: 'Paul'}))
})

When I try it this way, it tells me, that ‘data.elemMatch’ is not a function. :confused:

You need 1 more parenthesis after this.

data.elemMatch('example', ({name: 'Paul'}))
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.