Jan*_*ana 4 mongoose mongodb node.js
我的节点模型包含以下属性
firstName
lastName
age
address
Run Code Online (Sandbox Code Playgroud)
我需要使用mongoose find函数来使用firstName和lastName过滤用户.
我的UI只传递一个搜索参数.数据应按如下方式过滤
'fistName'喜欢'搜索参数'和lastName喜欢'搜索参数'.
我通过以下对象来查找函数.它对我不起作用.
var criteria = {
'firstName' : req.body.customerName ? { $regex: req.body.customerName, $options: 'i' } : null ,
'lastName' : req.body.customerName ? { $regex: req.body.customerName, $options: 'i' } : null
};
Run Code Online (Sandbox Code Playgroud)
Sha*_*Roy 12
如果你想,如果匹配得到的数据与两个字段的firstName和lastName,那么你可以使用$and运营商$regex.
var query = {$and:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}
Run Code Online (Sandbox Code Playgroud)
如果你想,如果匹配得到的数据与任何一个字段的firstName和lastName,那么你可以使用$or运营商$regex.
var query = {$or:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}
Run Code Online (Sandbox Code Playgroud)
所以可以试试这段代码:
var query = {}
if(req.body.customerName) {
query = {$or:[{firstName:{$regex: req.body.customerName, $options: 'i'}},{lastName:{$regex: req.body.customerName, $options: 'i'}}]}
}
ModelName.find(query , function (err, data) {
if(error) {
// return error
}
//return data
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7444 次 |
| 最近记录: |