最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

NodeJs FindbyId在一个对象中

IT培训 admin 3浏览 0评论

NodeJs FindbyId在一个对象中

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

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)
});

NodeJs FindbyId在一个对象中

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

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)
});

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论