Home > front end >  MongoDB: filter (findOne/updateOne..) by ObjectId not working or "ObjectId is not defined"
MongoDB: filter (findOne/updateOne..) by ObjectId not working or "ObjectId is not defined"

Time:11-14

None of the following filters worked when I tried to update a document, in JS/Node.js filtered by "_id", where the value is the generic ObjectId (ObjectId('6365050650c6be6d5d090135')) :

{_id : ObjectId(123....7890)}
{_id : ObjectId('123....7890')}
{_id : "ObjectId('123....7890')"}
  other variantions I came across

Nothing worked for me. I got ReferenceError: ObjectId is not defined or no errors.

CodePudding user response:

You need to be able to spawn new ObjectIds, so enable that first:

import { MongoClient, ObjectId } from "mongodb";

and filter like this:

{_id : new ObjectId('123....7890')}

enter image description here

Actually this is what MongoDB Compass "exports to language" (see screenshot above) when you filter

{_id: ObjectId('123....7890')}

I am pretty sure this is obvious to many, but it took me quite a while to resolve it, so I hope this saves you some time.

CodePudding user response:

Either use ObjectId from mongodb client like so:

import { ObjectId } from "mongodb";

{ _id: new ObjectId('6365050650c6be6d5d090135')}

or if you are using mongoose then:

{ _id: mongoose.Schema.Types.ObjectId('6365050650c6be6d5d090135') } 

or with mongoose you can directly pass in the objectid string and the mongoose model will handle it for you like so:

{ _id: '6365050650c6be6d5d090135' }

I am not sure if the above possible can be done with mongodb client too.

  • Related