我想使用查询字符串搜索我的用户存储库。
这应该返回具有相似用户名“kyogron”和相似电子邮件“kyogron@gmail”的所有用户
GET localhost:3000/users?username=kyogron&[email protected] /cdn-cgi/l/email-protection
这应该返回所有用户:
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 protected] /cdn-cgi/l/email-protection
// { username: "kyogron", email: "[email protected] /cdn-cgi/l/email-protection" }
//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);
});
});
这些是我正在努力解决的问题:
- 为什么迭代 req.query 对象不起作用?
- 我怎么说 mongoose 使用通配符(例如 kyo*)
如果有人能帮助我就好了:)
Regards
EDIT:
第二个问题可以用 $where 解决:
if (req.query.username) {
query.$where(function() {
return this.username === req.query.username; // here we need a regex check
});
}
这不起作用...有人能给我提示吗?
EDIT2:
没有用 $where 进行任何操作...但是我现在发现
query.where('username').regex();
我只需要寻找一个搜索正则表达式来查找相似的单词
EDIT3:
我找到了这个线程:如何使用“like”查询MongoDB? https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like我在 mongoosejs 组中询问如何使用 mongoose 做到这一点
EDIT4:
if (req.query.username) {
query.where('username').regex(new RegExp("\/"+req.query.username+"\/"));
}
我差一点就明白了。只需修复这个愚蠢的正则表达式......