is there a way to auto generate ObjectId when a mongoose Model is new'ed?


is there a way to declare a Model schema in mongoose so that when the model is new'ed the _id field would auto-generate?

for example:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectIdSchema = Schema.ObjectId;
var ObjectId = mongoose.Types.ObjectId;

var PersonSchema = new Schema({
    _id:            ObjectIdSchema,
    firstName:      {type: String, default: 'N/A'},
    lastName:       {type: String, default: 'N/A'},
    age:            {type: Number, min: 1}

var Person = mongoose.model('Person', PersonSchema);

at first, i thought great!, i'll just do

_id:    {type:ObjectIdSchema, default: new ObjectId()}

but of course that doesn't work, because new ObjectId() is only called on initialize of schema. so calling new Persion() twice creates two objects with the same _id value.

so is there a way to do it so that every time i do "new Person()" that a new ObjectId() is generated?

the reason why i'm trying to do this is because i need to know the value of the new person's _id value for further processing.

i also tried:

var person = new Person({firstName: "Joe", lastName: "Baz"});, doc, num){

even then, doc doesn't contain the ObjectId. but if i look in the database, it does contain it.

p.s. i'm using mongoose 2.7.1

p.p.s. i know i can manually create the ObjectId when creating the person as such:

var person = new Person({_id: new ObjectId(), firstName: "Joe", lastName: "Baz"});

but i rather not have to import ObjectId and have to new it every time i want to new a Person. guess i'm used to using the java driver for mongodb, where i can just create the value for the _id field in the Model constructor.

7/22/2012 11:47:57 PM

Accepted Answer

the moment you call var person = new Person(); person._id should give you the id (even if it hasn't been saved yet). Just instantiating it is enough to give it an id. You can still save it after, and that will store the id as well as the rest of the person object

7/23/2012 12:08:16 AM

Add the auto flag:

_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true,
    required: true,
    auto: true,


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow