有这样一个需求:根据URL中的query参数,来判断应该包含哪些查询条件。
使用场景
var _q = req.query;
// 当URL为 http://api.abc.com/group/filter?s=2
group.find({status:_q['s']});
// 当URL为 http://api.abc.com/group/filter?t=1&s=2
group.find({type:_q['t'],status:_q['s']});
请问find()
如何书写,才能满足查询条件?
我当前的做法
var _q = req.query, _qParams = [];
if(_q.hasOwnProperty("t")){
_qParams.push({"type":_q["t"]});
}
if(_q.hasOwnProperty("s")){
_qParams.push({"status":_q["s"]});
}
groups.find({$or:_qParams},{},{sort:{_id:-1},limit:50}).exec(function (err, data) {
if(!data || data.length == 0){
res.json({code: 404, msg: "Empty"});
}else{
res.json({code: 0, msg: "success", data: data, count: data.length});
}
});
但是执行了这条语句
res.json({code: 404, msg: "Empty"});
请各位高手赐教!
巴扎黑2017-04-17 15:19:01
The statement executed indicates that no result was found. Print the err to see if an error is reported, and then confirm whether the record in the database exists
In addition, the query conditions of your code below are different from what you mentioned above. The code below uses $or query, while the query above should be and query
var _q = req.query, _qParams = [];
if(_q.hasOwnProperty("t")){
_qParams.type = _q["t"];
}
if(_q.hasOwnProperty("s")){
_qParams.status=_q["s"];
}
groups.find(_qParams,null,{sort:{_id:-1},limit:50}).exec(function (err, data) {
if(!data || data.length == 0){
res.json({code: 404, msg: "Empty"});
}else{
res.json({code: 0, msg: "success", data: data, count: data.length});
}
});
groups.find({$or:_qParams},{},{sort:{_id:-1},limit:50});
There is another place to query, the second field, if all fields are returned , pass null, not {}
大家讲道理2017-04-17 15:19:01
@江立 I modified it, even if the data does not exist, all records are still returned.
var _q = req.query, _qParams = [];
if(_q.hasOwnProperty("t")){
_qParams.push({type:parseInt(_q["t"])});
}
if(_q.hasOwnProperty("s")){
_qParams.push({status:parseInt(_q["s"])});
}
groups.find(_qParams,null,{sort:{_id:-1},limit:50},function(err, data){
if(!data || data.length == 0){
res.json({code: 404, msg: "Empty"});
}else{
res.json({code: 0, msg: "Success", data: data, count: data.length});
}
});