我想用查询字符串搜索我的用户存储库。
这应该返回所有用户名为“kyogron”的用户和类似的电子邮件“kyogron @ gmail”
GET localhost:3000/users?username=kyogron&email=kyogron@gmail.com
这应该返回所有用户:
GET localhost:3000/users
我已经设法处理路由参数,但我一直在优化它:
app.get('/users', function(req, res) {
// creates a mongoosejs query object
var query = User.find({});
// to understand how expressjs handles queries:
// ?username=kyogron&email=kyogron@gmail.com
// { username: "kyogron", email: "kyogron@gmail.com" }
//console.log(req.query);
// this was one idea of optimizing the search query parameters
// this doesn't work don't know why I always get an array of ALL users
// even the key and value is right
Object.keys(req.query).forEach(function(key) {
query.select(key, req.query[key]);
});
// this was the way I was first handling the parameters, this works !!
//if (req.query.username) query.where('username', req.query.username);
//if (req.query.email) query.where('email', req.query.email);
// the rest of the query
query.select('username', 'email');
query.exec(function(err, users) {
if (err) throw err;
res.json(users);
});
});
这些是我正在与之抗争的问题:
如果有人可以帮助我,那会很好。)
此致
修改:
第二个问题可用$ where解决:
if (req.query.username) {
query.$where(function() {
return this.username === req.query.username; // here we need a regex check
});
}
Thos不起作用......有人可以给我一个暗示吗?
EDIT2:
没有用$ where管理任何东西......但我现在找到了
query.where('username').regex();
我只需要寻找一个搜索正则表达式来寻找相似的单词
EDIT3:
我找到了这个主题:How to query MongoDB with "like"?我在mongoosejs小组中询问我如何用mongoose做到这一点
EDIT4:
if (req.query.username) {
query.where('username').regex(new RegExp("\/"+req.query.username+"\/"));
}
我几乎得到了它。只需修复这个愚蠢的正则表达式......
答案 0 :(得分:1)
app.get('/users', function(req, res) {
var query = User.find({});
Object.keys(req.query).forEach(function(key) {
query.where(key).regex(new RegExp(req.query[key]));
});
/*
if (req.query.username) {
query.where('username').regex(new RegExp(req.query.username));
}
if (req.query.email) {
query.where('email').regex(new RegExp(req.query.email));
}*/
query.select('username', 'email');
query.exec(function(err, users) {
if (err) throw err;
res.json(users);
});
});
第一个没有用,因为我有一个拼写错误(.select()没有.where())。第二个是在额外的线程中找到的
我对选择的方法仍然有点不确定。
迭代req.query将允许代码可重用(可能作为前提条件路由参数 - 函数)但它很容易出错