Tommi Rahman Perdana
Tommi Rahman Perdana

Reputation: 21

Find documents by populate match result in mongoose

For Ecample, From this data with mongoose :

Data Students :

[{
  "_id": ObjectId("5afbb519a7fe344ff8db67e6"),
  "name":"Jack",
  "age":20
  ...
},{
  "_id": ObjectId("5afbb534a7fe344gf7db64e7"),
  "name":"Joni",
  "age":20
  ...
}]

Data Activities :

[{
  "_id": ObjectId("5afbb554a7fe344ff8db67e9"),
  "name":"Going to Market",
  "student": ObjectId("5afbb519a7fe344ff8db67e6")
  ...
},{
  "_id": ObjectId("5afbb784a7fe344gf7db64e2"),
  "name":"Playing with Friends",
  "student":ObjectId("5afbb534a7fe344gf7db64e7")
  ...
}]

I want to find a data base on conditions in populate with regex & This is what i am did :

let term = new Regex('Jack','i');        
let result = await Activities.find({})
            .populate('student', null, { name: { $regex: term } })
            .exec();

But the result is always return all data of Activites (The regex query doesn't work)

What Should I Do?

Upvotes: 2

Views: 3478

Answers (1)

Dark Knight
Dark Knight

Reputation: 1083

You should try with using match

let result = await Activities.find({})
            .populate({ path: 'student', match: { name: { $regex: term } } })
            .exec();

Upvotes: 2

Related Questions