Can not use custom ObjectId since mongodb driver 5

Since I upgraded to mongodb driver 5 for node js, I can not create custom object id.

This is the way it works with the driver 4.x:

import mongodb from 'mongodb';

const { ObjectId } = mongodb;

new ObjectId();


new ObjectId(stringHash);

But when I use now this approach I get validation errors:

    "keyword": "bsonType",
    "params": {
      "bsonType": "objectId"
    "message": "should be objectId got 641adae6a6e5c8128965ae9a",
    "instancePath": "/widgets/116/parentId",
    "schemaPath": "#/properties/widgets/items/properties/parentId/bsonType",
    "schema": "objectId",
    "data": "641adae6a6e5c8128965ae9a"
 .... etc

Hi @Anton_Tonchev and welcome to MongoDB community forums!!

I tried to insert a custom objectId for _id using the below code snippet and I was able to insert the data successfully into the collection.

const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const assert = require('assert');

const url = 'mongodb+srv://<username>:<password>';
const dbName = 'Test1';
const client = new MongoClient(url,  { useNewUrlParser: true });
.finally(async () => {await client.close();})

async function run() {

    await client.connect();
    console.log("Connected correctly to server");

    const db = client.db(dbName);

    const coll = db.collection("sample");
    let res = await coll.insertOne({_id: new ObjectId('6097a1c12714b94348359a2c'), a: 1});
    console.log(`Inserted Document _id: ${res.insertedId}`);


Connected correctly to server
Inserted Document _id: 6097a1c12714b94348359a2c

Please make sure, you have imported
const ObjectId = require('mongodb').ObjectId;
to the code.
The forum post has more details on the new features in the latest release. See release notes for more details.

NodeJs version: 5.1.0
MongoDB version: 6.0.5(Atlas Deployment)


Hi @Anton_Tonchev could you provide an actual stack trace for the underlying error? What exactly is trying to “validate” the ObjectId? This string is perfectly fine when constructing and ObjectId directly from the BSON library or importing it from the Driver.

Hi @Durran_Jordan and @Aasawari

Thanks for the reply, the problem seems to be at AJV, which I use to validate the documents before delivering them to the mongodb

AJV compared if the bsonType of the document is ObjectID but now it changed to ObjectId After knowing this I fixed the validation check, and now it works fine.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.