How I can create a model instance in the same model's schema method? How I can create a model instance in the same model's schema method? mongoose mongoose

How I can create a model instance in the same model's schema method?


You were on the right track; this is the Model the schema is registered as within a schema.statics method, so your code should change to:

Schema.statics.createInstance = function (name, pass) {    var newPerson = new this();    newPerson.name = name;    newPerson.pass = pass;    newPerson.save();    return newPerson;}

And Leonid is right about handling the save callback, even if it's only to log errors.


You almost answered your question. The only problem with your code is that you don't have a registered model at this point. But you can use mongoose.model to fetch it dynamically:

Schema.statics.createInstance = function (name, pass) {    var newPerson = new db.model('Person'); // <- Fetch  model "on the fly"    newPerson.name = name;    newPerson.pass = pass;    newPerson.save();    return newPerson;}

Ow. And consider handling save callback. You can't be sure that save operation won't fail.