我正在尝试在节点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 console.log(err)
}
if(result){
response = {status:'success',data:result};
} else{
response = {status:'fail'};
}
res.send(response);
});
};
我正在尝试搜索firstname
,我确信我错了。
任何人都可以帮助我
答案 0 :(得分:2)
您可以试试query
来获取firstname
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);
});
答案 1 :(得分:1)
要执行文本搜索,请确保首先为搜索字段创建了文本索引。
像:
db.collection('profile').createIndex( { firstName: "text" } );
然后您可以对该字段进行文本搜索。
// params.id should be like "shaishab"
// but better to use req.query.firstName instead of req.params.id
// and you should change your route for that
record.find({$text: {$search: params.id}}, (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);
});
或没有创建文本索引,您可以使用$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);
});