我正在尝试为我的应用添加搜索功能。我写了两个函数,一个是工作,另一个不是。我试图搞清楚,但没有运气。
这是工作职能:
// Add Search Functionility
router.get('/:searchTerm', ensureLoggedIn, (req, res) => {
let searchTerm = req.params.searchTerm;
let regex = new RegExp(searchTerm.replace(/[w]/g, ":a"), 'g');
let loggedUser = req.user.id;
User.findById(loggedUser).exec()
.then(foundUser => {
if (foundUser.role != 'admin') {
if (isNaN(searchTerm)) {
User.findById(loggedUser).populate({path: 'permits', match: {'name': regex, isAuth: true}}).exec()
.then(populatedUser => res.json(populatedUser.permits))
.catch(err => res.send(err));
} else {
User.findById(loggedUser).populate({path: 'permits', match: {'num': regex, isAuth: true}}).exec()
.then(populatedUser => res.json(populatedUser.permits))
.catch(err => res.send(err));
}
} else {
if (isNaN(searchTerm)) {
Permit.find({'name': regex, isAuth: true}).populate('authBy', 'username').sort({date: 'desc'}).exec()
.then(foundPermits => res.json(foundPermits))
.catch(err => res.send(err));
} else {
Permit.find({'num': regex, isAuth: true}).populate('authBy', 'username').sort({date: 'desc'}).exec()
.then(foundPermits => res.json(foundPermits))
.catch(err => res.send(err));
}
}
})
});
这是不起作用的功能:
// Add Search Functionility
router.get('/:searchTerm', ensureLoggedIn, (req, res) => {
let searchTerm = req.params.searchTerm;
let regex = new RegExp(searchTerm.replace(/[w]/g, ":a"), 'g');
let loggedUser = req.user.id;
function searchPermitsBy(query) {
User.findById(loggedUser).exec()
.then(foundUser => {
if (foundUser.role != 'admin') {
User.findById(loggedUser).populate({path: 'permits', match: {query: regex, isAuth: true}}).exec()
.then(populatedUser => res.json(populatedUser.permits))
.catch(err => res.send(err));
} else {
Permit.find({query: regex, isAuth: true}).populate('authBy', 'username').sort({date: 'desc'}).exec()
.then(foundPermits => res.json(foundPermits))
.catch(err => res.send(err));
}
})
.catch(err => res.send(err));
}
isNaN(searchTerm) ? searchPermitsBy('name') : searchPermitsBy('num');
});
你能帮我找一下这个问题吗?感谢。
答案 0 :(得分:1)
问题出在您的query
变量中。
您不能使用变量直接向json添加密钥。
你必须使用
json[varContainingKey]=value
// Add Search Functionility
router.get('/:searchTerm', ensureLoggedIn, (req, res) => {
let searchTerm = req.params.searchTerm;
let regex = new RegExp(searchTerm.replace(/[w]/g, ":a"), 'g');
let loggedUser = req.user.id;
function searchPermitsBy(query) {
User.findById(loggedUser).exec()
.then(foundUser => {
//create match variable
var match = {isAuth:true}
//Add query to match variable
match[query]=regex
if (foundUser.role != 'admin') {
User.findById(loggedUser).populate({path: 'permits', match: match}).exec()
.then(populatedUser => res.json(populatedUser.permits))
.catch(err => res.send(err));
} else {
Permit.find(match).populate('authBy', 'username').sort({date: 'desc'}).exec()
.then(foundPermits => res.json(foundPermits))
.catch(err => res.send(err));
}
})
.catch(err => res.send(err));
}
isNaN(searchTerm) ? searchPermitsBy('name') : searchPermitsBy('num');
});