2017-10-05 189 views
2

我使用node-mongodb-native来实现MongoDB查询功能。我需要执行一个查询,如果tag相匹配的部分或组合firstNamelastName这样的:node.js - mongodb native中的RegExp

filter50WithTagSkip(tag, skip) { 
     return new Promise((resolve, reject) => { 
      const regex = new RegExp(tag, 'g'); 
      const or_criteria = [ 
       { firstName: { $regex: regex, $options: 'i' } }, 
       { lastName: { $regex: regex, $options: 'i' } }, 
       { fullName: { $regex: regex, $options: 'i' } }, 
       { email: { $regex: regex, $options: 'i' } }, 
       { phone: { $regex: regex, $options: 'i' } } 
      ]; 
      this._db.collection(this._table) 
       .aggregate({ 
        $project: { 
         deleted: 1, 
         firstName: 1, 
         lastName: 1, 
         email: 1, 
         phone: 1, 
         fullName: { $concat: ['$firstName', ' ', '$lastName'] } 
        } 
       }).match({ 
        $or: or_criteria, 
        deleted: false 
       }) 
       .skip(skip) 
       .limit(50) 
       .toArray((err, res) => { 
        if (err) { 
         this._logger.error(err); 
         reject(err); 
        } else { 
         resolve(res); 
        } 
       }); 
     }); 
    } 

有了这些样本:

{ 
firstName: "first1", 
lastName: "last1" 
}, 
{ 
firstName: "first2", 
lastName: "last2" 
} 

如果tagfirst结果有两个文档。但是,如果我将firstNamelastName条件注释掉,则认为它们不是必需的,因为RegExp将在组合字符串上应用模式,结果是一个空数组。我感到很困惑

回答

0

我想我找到了自己的解决方案,这是由这个库来初始化汇总查询的正确方法:

filter50WithTagSkip(tag, skip) { 
     return new Promise((resolve, reject) => { 
      const regex = new RegExp(tag, 'g'); 
      const or_criteria = [ 
       // { firstName: { $regex: regex, $options: 'i' } }, 
       // { lastName: { $regex: regex, $options: 'i' } }, 
       { fullName: { $regex: regex, $options: 'i' } }, 
       { email: { $regex: regex, $options: 'i' } }, 
       { phone: { $regex: regex, $options: 'i' } } 
      ]; 
      const project_criteria = { 
       deleted: 1, 
       // firstName: 1, 
       // lastName: 1, 
       email: 1, 
       phone: 1, 
       fullName: { $concat: ['$firstName', ' ', '$lastName'] } 
      }; 
      const match_criteria = { 
       $or: or_criteria, 
       deleted: false 
      }; 
      const aggregate_criteria = [{ $project: project_criteria }, { $match: match_criteria }]; 
      this._db.collection(this._table) 
       .aggregate(aggregate_criteria) 
       .skip(skip) 
       .limit(50) 
       .toArray((err, res) => { 
        if (err) { 
         this._logger.error(err); 
         reject(err); 
        } else { 
         resolve(res); 
        } 
       }); 
     }); 
    }