0
  const cCurser = await client
    .db("Database")
    .collection("Collection")
    .findOne({
        _id: ObjectId(Filter)       
    }).then(function(item){
        Obj = item;}
    );

I'm trying to query the MongoDB by the _id but it returns Promise { }. please help me to retrieve the data in it. Error detected:ReferenceError: ObjectId is not defined

2 Answers 2

1

add this before your query:

import mongoose from 'mongoose';
const { ObjectId } = mongoose.Types;

OR:

use this:

  const cCurser = await client
    .db("Database")
    .collection("Collection")
    .findOne({
        _id: new mongoose.Types.ObjectId(Filter)       
    }).then(function(item){
        Obj = item;}
    );
Sign up to request clarification or add additional context in comments.

1 Comment

I'm using the mongoose library, is there anything I can do without a mongoose. sorry for As Im new to Mongo
0

Firstly, don't mix await syntax with the then syntax.

Either use await

let Obj = null;
const cCurser = await client
    .db("Database")
    .collection("Collection")
    .findOne({
        _id: ObjectId(Filter)       
    });

//Use Obj

Or the then syntax. Here you will have to write the rest of the code dependent on Obj inside then().

let Obj = null;
const cCurser = client
    .db("Database")
    .collection("Collection")
    .findOne({
        _id: ObjectId(Filter)       
    }).then(function(item){
        Obj = item;
         //Use Obj
        }
    );

Also based on your edit,it seems you have not imported ObjectId method from Mongo.

let mongo = require('mongodb');
let ObjectId = mongo .ObjectID
```

1 Comment

I changed according to your instructions still I'm getting Error detected:ReferenceError: ObjectId is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.