Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs FindbyId in an object

I want to retrieve data from a specific local object

var db=[
{
    "_id": "543adb9c7a0f149e3ac29438",
    "name": "user1",
    "email": "[email protected]"
},
{
    "_id": "543adb9c7a0f149e3ac2943b",
    "name": "user2",
    "email": "[email protected]"
}

]

i did this to find a specific user only by id, and in Postman i always get error 500

app.get('/msg/:id',(req, res) =>{
    db.findById(req.params.id, function(err, dba) {
            if (err)
            res.send(err)
            res.json(dba)
  });
});
like image 829
Taieb Avatar asked Jan 31 '26 04:01

Taieb


1 Answers

findById is a method of Mongoose library, not a method of JavaScript objects. If you want to use it, you should implement it by yourself in JavaScript objects

If db is a local object and not a db connection, you can use 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)
});
like image 135
David Vicente Avatar answered Feb 02 '26 16:02

David Vicente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!