NodeJs FindbyId在一个对象中

问题描述 投票:2回答:1

我想从特定的本地对象中检索数据

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)
  });
});
javascript node.js rest express
1个回答
2
投票

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)
});
© www.soinside.com 2019 - 2024. All rights reserved.