简体   繁体   English

填充不适用于 $regex mongodb

[英]Populate does not work with $regex mongodb

I have this query which is working fine but child document is not populating when i use regex我有这个查询工作正常但是当我使用正则表达式时子文档没有填充

let u = new RegExp(`${req.params.username}`, 'i');

let user = await User.findOne({
  userName: { $regex: u },
}).populate({
  path: 'profiles',
  populate: {
    path: 'companyId',
    match: { _id: { $exists: true } },
  },
});

It always return child field as empty它总是将子字段返回为空

This query is working fine without regex这个查询在没有正则表达式的情况下工作正常

let user = await User.findOne({
  userName: req.params.username,
}).populate({
  path: 'profiles',
  populate: {
    path: 'companyId',
    match: { _id: { $exists: true } },
  },
});

Please try the following code, this is tested code, '.*' means if the string matching anywhere like the string is lookup and I want to search with the look it will return all the records which contain look.请尝试下面的代码,这是经过测试的代码,'.*'表示如果字符串匹配任何地方像字符串是查找并且我想用外观搜索它会返回所有包含外观的记录。

let user = await User.findOne({
  userName: {
        $regex: `.*${req.params.username}.*`,
        $options: 'i'
      },
}).populate({
      path: 'profiles',
      populate: {
      path: 'companyId',
      match: { _id: { $exists: true } },
   },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM