我在线上找到了一个教程,这里有一种简单的方法来进行部分搜索。我想做的是,当某人只写geor
时,它将找到一个名为george
db.stores.find({storeName : {$regex : /Geor/}}).pretty()
但是我不知道如何在搜索中实现它。我尝试了一些尝试,但一切都以错误告终。
这是我的控制者:
/**
* GET /admin/users/:page
* Find users
*/
exports.findUsers = (req, res, next) => {
const perPage = 13
const page = Number(req.params.page) || 1
var query = {};
const possibleQueryProps = [{
"key": "id",
"queryKey": "_id"
},
{
"key": "email",
"queryKey": "email"
},
{
"key": "firstname",
"queryKey": "profile.firstname"
},
{
"key": "lastname",
"queryKey": "profile.lastname"
},
{
"key": "location",
"queryKey": "profile.location"
},
{
"key": "status",
"queryKey": "profile.status"
}
];
possibleQueryProps.forEach(prop => {
if (req.query[prop.key]) {
query[prop.queryKey] = req.query[prop.key];
}
});
console.log(query)
User
.find(query)
.skip((perPage * page) - perPage)
.limit(perPage)
.exec(function (err, users) {
User.countDocuments(query).exec(function (err, count) {
if (err) return next(err)
res.render('admin/users', {
layout: "admin",
users: users,
query: req.query,
active: {
users: true
},
current: page,
pages: Math.ceil(count / perPage),
helpers,
pagesArr: Array.from(Array(((Math.ceil(count / perPage)))).keys()).map(i => 1 + i),
pagination: core.pagination(page, (Math.ceil(count / perPage))),
})
})
})
};
我将感谢您的任何建议。
答案 0 :(得分:1)
我认为它将起作用:
possibleQueryProps.forEach(prop => {
if (req.query[prop.key]) {
query[prop.queryKey] = {$regex : new RegExp('.*' + req.query[prop.key] + '.*')};
}
});