tilly
tilly

Reputation: 2610

Mongodb document with array of objects property: how match property of this array?

Below is an image of what my user MongoDB document looks like. I have a skills array which contains objects with the follwing structure.

{
name: String,
points: Number,
skill: Schema.Types.ObjectId
}

Here's a screenshot of an actual user document, you can see the skill with the name html

enter image description here

Now I want to create a search query that would match the name property of one these objects in the skills array. e.g if my input is htm it would match with a user that has a skill with the name html. I tried it the way below, but it doesn't seem to be working. Can someone suggest me how to successfully do this?

const createSkillsQuery = (user, input) => User.find({
  $and: [
    { skills: { name: { $regex: input, $options: 'i' } } },
    { _workspace: user._workspace }
  ]
}).select('profile_pic full_name email created_date');

Upvotes: 0

Views: 32

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You need to use the dot notation here.

"skills.name": { $regex: input, $options: 'i' }

Upvotes: 1

Related Questions