How to convert string to ObjectId with Node.js Mongoose?

Sometimes, we want to convert string to ObjectId with Node.js Mongoose.

In this article, we’ll look at how to convert string to ObjectId with Node.js Mongoose.

How to convert string to ObjectId with Node.js Mongoose?

To convert string to ObjectId with Node.js Mongoose, we can use the mongoose.Types.ObjectId method.

For instance, we write

const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

to call mongoose.Types.ObjectId with the ObjectId string to convert the string to an ObjectId.

Conclusion

To convert string to ObjectId with Node.js Mongoose, we can use the mongoose.Types.ObjectId method.