这是我的标准用法。
它使用 $or 运算符。
var query = req.query.query,
queryArr = query.split(' '),
first_name,
last_name;
// Check if it is split into a first and last name
if (queryArr.length === 2) {
//create regex for first and last name
first_name = new RegExp(queryArr[0], 'i');
last_name = new RegExp(queryArr[1], 'i');
}
query = new RegExp(query, 'i');
var dbQuery = {
// Searches first_name or last_name
$or: [
{
// Searches first name based on whole query or first_name query
$or: [
{
first_name: query
},
{
first_name: first_name
}
]
},
{
// Searches last_name based on whole query or last_name query
$or: [
{
last_name: query
},
{
last_name: last_name
}
]
}
]
};
db.users.find(dbQuery, function (error, response) {
res.send(200, {
success: true,
body: response
});
});