Categories
JavaScript Answers

How to generate an ObjectId with Mongoose?

Spread the love

Sometimes, we want to generate an ObjectId with Mongoose.

In this article, we’ll look at how to generate an ObjectId with Mongoose.

How to generate an ObjectId with Mongoose?

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

For instance, we write

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

to create an ObjectId with mongoose.Types.ObjectId and assign it to id.

We don’t need new before mongoose.Types.ObjectId before Mongoose v6.

Conclusion

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

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 *