5
我想用查詢字符串搜索我的用戶存儲庫。Expressjs:搜索查詢api
這將返回所有用戶都具有相似的用戶名「kyogron」以及類似的電子郵件「kyogron @ gmail的」
GET localhost:3000/users?username=kyogron&[email protected]
這將返回所有用戶:
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]
// { username: "kyogron", email: "[email protected]" }
//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);
});
});
這些是p roblems我與之戰鬥:
- 爲什麼不迭代req.query對象工作?
- 我怎麼說貓鼬使用通配符(如:京*)
將是很好,如果有人可以幫助我:)
問候
編輯:
第二個問題可以用$解決:其中:
if (req.query.username) {
query.$where(function() {
return this.username === req.query.username; // here we need a regex check
});
}
Thos不起作用...有人可以給我一個提示嗎?
EDIT2:
沒有管理與$什麼地方......但我現在發現
query.where('username').regex();
我只是要尋找一個搜索正則表達式,看起來類似的話
編輯3:
我發現此線程:How to query MongoDB with "like"?我的mongoosejs組問我怎麼能做到這一點與貓鼬
EDIT4:
if (req.query.username) {
query.where('username').regex(new RegExp("\/"+req.query.username+"\/"));
}
我幾乎得到了它。只要有解決這個愚蠢的正則表達式...