Mongodb 通过字段查询Mongoose
我正试图在express中查询这个猫鼬对象“Order”。但是,当我在find的括号之间添加querystring变量时,它就不起作用了。我对如何解决这个问题的文档有点迷茫Mongodb 通过字段查询Mongoose,mongodb,express,mongoose,Mongodb,Express,Mongoose,我正试图在express中查询这个猫鼬对象“Order”。但是,当我在find的括号之间添加querystring变量时,它就不起作用了。我对如何解决这个问题的文档有点迷茫 router.get('/allorders', jwtAuth, function(req,res,next) { const userID = req.user.username; const querystring = "{orderedByUser: '" + userID + "'}"; //Or
router.get('/allorders', jwtAuth, function(req,res,next) {
const userID = req.user.username;
const querystring = "{orderedByUser: '" + userID + "'}";
//Order.find() works
Order.find(querystring)
.then(orders =>{
res.json(orders).end();
}).catch( err=> {
res.status(500).json({error: 'Something went wrong!'});
});
});
find
接受查询对象,而不是字符串。因此,它应该是:
Order.find({orderedByUser: userID}).then(...
您知道原因,因为需要传递给
Model.find()
的条件必须是对象
:
Model.find()
参数
- 条件«对象»
- [投影]«对象|字符串»要返回的可选字段,请参阅Query.prototype.select()
- [选项]«对象»可选请参见Query.prototype.setOptions()
- [回调]«函数»
- «查询»
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes immediately, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
在代码中,将字符串
传递给该方法,而不是对象
然后,试试这个:
router.get('/allorders',jwtAuth,函数(req,res,next){
const userID=req.user.username;
const conditionsObject={orderedByUser:userID};//已修复
//Order.find()有效
Order.find(conditionsObject)//已修复
。然后(订单=>{
res.json(orders.end();
}).catch(错误=>{
json({error:'出了问题!'});
});
});代码>