How can I generate an ObjectId with mongoose?

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.


Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:

var id = new mongoose.Types.ObjectId();

You can read more about the Types object at Mongoose#Types documentation.

Leave a Comment