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>@cluster0.sqm88.mongodb.net/?retryWrites=true&w=majority';
const dbName = 'Test1';
const client = new MongoClient(url, { useNewUrlParser: true });
run()
.catch(console.dir)
.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});
assert(res.insertedId);
console.log(`Inserted Document _id: ${res.insertedId}`);
}
Output:
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.
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.
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.