How to convert a string to Object Id in Node.js MongoDB native driver?

Sometimes, we want to convert a string to Object Id in Node.js MongoDB native driver.

In this article, we’ll look at how to convert a string to Object Id in Node.js MongoDB native driver.

How to convert a string to Object Id in Node.js MongoDB native driver?

To convert a string to Object Id in Node.js MongoDB native driver, we can use the ObjectId function.

For instance, we write

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

const y = ObjectId("507f191e810c19729de860ea")

to convert the string '507f191e810c19729de860ea' to an MongoDB object ID with ObjectId and assign it to y.

Conclusion

To convert a string to Object Id in Node.js MongoDB native driver, we can use the ObjectId function.