James Bandenburg
James Bandenburg

Reputation: 39

Mongoose/Express - problems using findById()

I have a database of activities in MongoDB, had all the basic CRUD operations working fine but now at the point in developing the front end of the app where I need to do a GET request for a single activity in the database. I have working PUT and DELETE requests for single activities but for some reason the GET one just isn't playing ball - it's returning an array of objects rather than a single object with that ID.

I'm currently using Postman to make the requests while I iron this problem out. Mongoose version is 5.12.13.

router.get('/:id', async (req, res) => {
try {
    const activity = await Activities.findById(req.params.id)
    res.json(activity).send()
} catch (error) {
    res.send(error.message)
}

})

Then making a request using Postman to http://localhost:5000/api/activities?id=60968e3369052d084cb6abbf (the id here is just one I've copied & pasted from an entry in the database for the purposes of troubleshooting)

I'm really stumped by this because I can't understand why it's not working! The response I get in Postman is an array of objects, like I said, which seems to be the entire contents of the database rather than just one with the queried ID...

Upvotes: 0

Views: 645

Answers (1)

Lee Brindley
Lee Brindley

Reputation: 6472

Try calling exec on your findById, findById returns a query, you need to call exec to execute your query.

Without the call to the exec function, your 'activity' variable is a mongoose query object.

router.get('/:id', async (req, res) => {
    try {
        const activity = await Activities.findById(req.params.id).exec();
        res.json(activity).send()
    } catch (error) {
        res.send(error.message)
    }
});

Docs for findById

https://mongoosejs.com/docs/api.html#model_Model.findById

Edit:

As righty spotted by Dang, given your code is inspecting req.params the URL you're calling needs updating to:

http://localhost:5000/api/activities/60968e3369052d084cb6abbf

Upvotes: 1

Related Questions