如何在Node.js MongoDB中执行搜索
我试图在node js中对我的列表执行搜索,我下面的代码受此约束如何在Node.js MongoDB中执行搜索,node.js,mongodb,express,Node.js,Mongodb,Express,我试图在node js中对我的列表执行搜索,我下面的代码受此约束 exports.searchlistbyfirstname = function (req, res) { var params = req.params; var record= db.collection('profile'); record.find( { $text: { $search: params.id} }, (err, result) => { if (err){ return cons
exports.searchlistbyfirstname = function (req, res) {
var params = req.params;
var record= db.collection('profile');
record.find( { $text: { $search: params.id} }, (err, result) => {
if (err){ return console.log(err)
}
if(result){
response = {status:'success',data:result};
} else{
response = {status:'fail'};
}
res.send(response);
});
};
我正在尝试搜索firstname
,我肯定我搞错了
有人能帮我执行文本搜索吗?请确保首先为搜索字段创建了文本索引 比如: 然后,您可以对该字段执行文本搜索 或如果不创建文本索引,您可以使用
$regex
运算符搜索firstName
record.find({firstName: { $regex: req.params.id, $options: 'i' } }, (err, result) => {
if (err) {
console.log(err)
return res.status(400).send({status: 'fail', error: err});
}
if (result) {
response = {status: 'success', data: result};
} else {
response = {status: 'fail'};
}
res.send(response);
});
您可以尝试此
查询
以获取您的名字
record.find({
firstname: {
$regex: params.id
}
}, (err, result) => {
if (err) {
return console.log(err)
}
if (result) {
response = {
status: 'success',
data: result
};
} else {
response = {
status: 'fail'
};
}
res.send(response);
});
firstname查询在哪里?我很困惑,params.id有我的firstname值,我应该如何为此编写查询?谢谢abdulbarik,它工作得很好,$regex用于什么?它为查询中的模式匹配字符串提供正则表达式功能。请参阅文档
record.find({firstName: { $regex: req.params.id, $options: 'i' } }, (err, result) => {
if (err) {
console.log(err)
return res.status(400).send({status: 'fail', error: err});
}
if (result) {
response = {status: 'success', data: result};
} else {
response = {status: 'fail'};
}
res.send(response);
});
record.find({
firstname: {
$regex: params.id
}
}, (err, result) => {
if (err) {
return console.log(err)
}
if (result) {
response = {
status: 'success',
data: result
};
} else {
response = {
status: 'fail'
};
}
res.send(response);
});