node.jsmongodbnosqlbackendobjectid

ObjectId is not a function in MongoDB


I just saw a blog on how to retrive a particular document by the ID of the document.

But here the code just does not seem to work for some reason.

It works always, can you people tell me why this is happening?

Code:

app.post('/api/get-list-data', (req, res) => {
  const listID = req.body.listID;
  client.connect(async err => {
    const collection = client.db('to-do-lists').collection('made');
    const data = await collection.findOne({
      _id: new ObjectId()
    })

    if (data) {
      res.send(data);
    } else {
      res.send({
        success: false
      });
    }
  })
})

Any help would be greatful!


Solution

  • I fixed my issue by getting the ObjectId in the top of the page like this:

    const { ObjectId } = require('mongodb');