Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findById returning a list of documents instead of a single result

I'm trying to get an item object via its object Id from mongodb, but when i tried to call that route in postman it gives me a list of every single object in the database (total of 4 objects) instead of the expected one object.

Here's the function i created for getting one object from the database

getEvent : function(id,callback)
{
   EventModel.findById(id,callback);
},

And Below is my routes

router.get('/events/:id',function(req,res)
{
    var id = req.params.id;
    db.getEvent(id,function(err,event)
    {
        if(err)
        {
            console.log("Error processing data");
        }
        else{
            console.log("get one event is called");
            res.send(event)`enter code here`;
        }
    })
});

And Finally Below is the result

Postman Test Result

like image 216
Dave Avatar asked Jan 21 '26 06:01

Dave


1 Answers

The code is correct, the way you are making request is wrong

Your Format :

http://localhost:3000/events?id=someid

id = someID in the URL represents a GET query parameter.

If you are using wildcard parameters like :id in the route, then the request URL should be :

http://localhost:3000/events/someid

someid will now be present in req.params.id

You are getting all the objects is because the variable id is undefined in your case, undefined parameters are omitted by default. So it is same as calling : EventModel.findById({}, callback)

Thanks

like image 100
Narasimha Prasanna HN Avatar answered Jan 22 '26 20:01

Narasimha Prasanna HN