Home > Mobile >  ObjectId is not a function in MongoDB
ObjectId is not a function in MongoDB

Time:08-01

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!

CodePudding user response:

ObjectId is a global in mongo-cli but not in the node environment. You can use exported function ObjectId from the mongodb package to create a new ObjectId instance.

        const data = await collection.findOne({ _id: mongo.ObjectId() })

You may also pass a valid hex representation of an objectID as an argument (assuming that listID is one)

        const data = await collection.findOne({ _id: mongo.ObjectId(listID) })

You also need to import the mongodb package before using the statement above for this to work.

const mongo = require('mongodb')

CodePudding user response:

Try to follow example:

import { ObjectId } from "bson"

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 BSON.ObjectId('3r6a9f26x')
    }).toArray();
    if (data) {
      res.send(data);
    } else {
      res.send({
        success: false
      });
    }
  })
})

Reference:

  • Related