2017-10-05 190 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); 
        } 
       }); 
     }); 
    }