Home > Mobile >  MongoDb query by _id using Node
MongoDb query by _id using Node

Time:10-04

  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

CodePudding user response:

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;}
    );

CodePudding user response:

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
```
  • Related