Home > Net >  Can't get to query MongoDB's ObjectId using Cypress
Can't get to query MongoDB's ObjectId using Cypress

Time:10-29

I'm trying to execute the following query

db.getCollection('name').find({_id : ObjectId("hereGoesAnId")})

I'm using mongodb module and use cy.task to query the db each time. This is working properly. In fact if I change id for another attribute to query, it will work like a charm. Problem is I can only identify the task by this id and the ObjectId is the one that's giving me issues.

If I try sending the query this way:

const result = await.collection.find({_id: `ObjectId(${varName})`}).toArray()

the result comes empty because it interprets ObjectId as a string and does not find anything.

However if I do it this way:

const result = await.collection.find({_id: ObjectId(`${varName}`)}).toArray()

I get an error saying "ObjectId is not defined...

I'm new to mongo and I'm not sure if there's a workaround for this?

CodePudding user response:

Top of the your code add this:

const { ObjectId } = require('mongodb');
  • Related