node.jsmongodbobjectid

Why ObjectID is not defined in MongoDB?


I try to query my MongoDB by finding particular "_id" but new ObjectID does not do the trick. And I try to create a variable hold a random ObjectID by "var obj = new ObjectID()" which does not work as well. Then I check my MongoDB version and it is up to date (db version v4.0.2). Server connection works fine. Any thoughts? Thanks.

My collection:

[
  {
    "_id": "5bc9fe6683dfb93706fe8a24",
    "name": "Luis",
    "occupation": "Doctor"
  },
  {
    "_id": "5bc9fe6683dfb93706fe8a25",
    "name": "Peter",
    "occupation": "Student"
  }
]

Mangodb code:

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



MongoClient.connect('mongodb://localhost:27017/NewApp',(err, client) => {

    if(err){
        return console.log("Unable to connect to MongoDB server");
    }


    console.log("Connect to MongoDB server");
    const db = client.db('NewApp');


    db.collection('Users').find({"_id": new ObjectID("5bc9fe6683dfb93706fe8a24")}).toArray().then((data) => {
        console.log(JSON.stringify(data, undefined, 2));

    },(error) => {

        if(error){console.log("Unable to fetch the data", error)}
    });


    client.close();
});

Error:

Connect to MongoDB server
/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
      throw err;
      ^

ReferenceError: ObjectID is not defined
at MongoClient.connect ...

Solution

  • Just replace first line of your code with

    const { MongoClient, ObjectID } = require('mongodb');
    

    You need to import ObjectID class in order to use it. You can see the list of all exports here: https://github.com/mongodb/node-mongodb-native/blob/master/index.js