Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *