How to generate an ObjectId with Mongoose?

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.