我想从特定的本地对象中检索数据
var db=[
{
"_id": "543adb9c7a0f149e3ac29438",
"name": "user1",
"email": "[email protected]"
},
{
"_id": "543adb9c7a0f149e3ac2943b",
"name": "user2",
"email": "[email protected]"
}
]
我这样做只是通过id找到一个特定的用户,而在Postman我总是得到错误500
app.get('/msg/:id',(req, res) =>{
db.findById(req.params.id, function(err, dba) {
if (err)
res.send(err)
res.json(dba)
});
});
findById是Mongoose库的一种方法,而不是JavaScript对象的方法。如果要使用它,您应该在JavaScript对象中自己实现它
如果db是本地对象而不是数据库连接,则可以使用find
app.get('/msg/:id',(req, res) =>{
var dba = db.find(element => element._id == req.params.id);
if(dba) res.json(dba);
else res.sendStatus(404)
});