MongoDB find by _id

Tags: , , ,



I’m building a Node.JS app, and i have a function that returns all the records if none of the queries were sent and, if sent, it returns all the records satisfying my query. Here’s my code:

const express = require('express');
const mongodb = require('mongodb');

const router = express.Router();

router.get('/', async (req, res) => {
    const items = await loadItemsCollection();
    const params = req.query; 
    if (Object.keys(params).length != 0) {
        console.log(params);
        res.send(await items.find(params).toArray());
    }
    else res.send(await items.find({}).toArray());
});

async function loadItemsCollection() {
    const client = await mongodb.MongoClient.connect('mongodb+srv://mynickname:mypassword@voda-delivery.oefbx.mongodb.net/voda-delivery?retryWrites=true&w=majority', {
        useNewUrlParser: true
    });

    return client.db('voda-delivery').collection('items');
}

module.exports = router;

Why i got an empty array returned when my param is { _id: ‘5f0218093e6f27870a6d5db2’ }? When I’m querying other properties e.g. { name: ‘1l water’ } it works as needed. console logs an id, all the records

Answer

You need to convert the ID from string to ObjectID:

const ObjectID = require("mongodb").ObjectID;
...
await items.find({ _id: ObjectID('5f0218093e6f27870a6d5db2') }).toArray()


Source: stackoverflow