node.js – mongodb native中的RegExp

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

 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将在组合string上应用模式,结果是一个空数组。 我感到很困惑

我想我自己find了解决scheme,这是通过这个库初始化聚合查询的正确方法:

 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); } }); }); }