我试图在查询结果中找到我找到正则表达式的字段,例如:
如果我在 facebook 字段中找到结果;
假设我的 req.body.key = 'crazy' 并且在我的数据库中我的 facebook 字段中有 'crazy' 。我希望作为查询结果,我的 CitizenProfile 模型包含更多我找到结果的字段。在本例中,字段名称为“facebook”
观察:此查询已经给出了模型,我只需要找到与正则表达式匹配的字段或字段名称。 这能实现吗?谢谢!
app.post('/v1/profile/search', (req, res) => {
async.waterfall([
function (next) {
CitizenProfile.find({
$or: [{'first_name': {$regex: req.body.key, $options:'i'}}, {'middle_name': {$regex: req.body.key, $options:'i'}},
{'last_name': {$regex: req.body.key, $options:'i'}}, {'email': {$regex: req.body.key, $options:'i'}},
{'facebook': {$regex: req.body.key, $options:'i'}}, {'linkedin': {$regex: req.body.key, $options:'i'}},
{'skills': {$regex: req.body.key, $options:'i'}}],
'id_citizen': {$ne: req.body.id_citizen},
'is_hidden': {$ne: true}
})
.exec(function (err, data) {
...
最佳答案
我不认为 MongoDB 有这种功能(如果我错了,请纠正我)。
由于您只是取回与正则表达式匹配的文档,因此您必须再次对这些相同的文档应用正则表达式才能查找字段。
未经测试,但我认为你会做类似的事情
let regex = new RegExp(req.body.key, 'i');
CitizenProfile.find({
$or: [
{ 'first_name': regex },
{ 'middle_name': regex },
{ 'last_name': regex },
{ 'email': regex },
{ 'facebook': regex },
{ 'linkedin': regex },
{ 'skills': regex }
],
'id_citizen': { $ne: req.body.id_citizen },
'is_hidden': { $ne: true }
}).exec(function (err, profiles) => {
// loop through found documents
profiles.forEach(function (profile) {
profile = profile.toJSON();
// filter fields based on regular expression
let keys = Object.keys(profile).filter(k => regex.test(profile[k]));
// do something with keys
console.log(keys);
});
});
关于javascript - Mongoose 查询查找,结果是我找到结果的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482528/