通过猫鼬匹配结果查找文档

时间:2018-06-26 09:13:33

标签: node.js mongodb express mongoose mongoose-populate

对于Ecample,从该数据中获得猫鼬:

数据学生

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

数据活动

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

我想找到一个用正则表达式填充条件的数据库,这就是我所做的:

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

但是结果总是返回 Activites 的所有数据(正则表达式查询无效)

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您应该尝试使用match

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