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

model, mongoose, node.js

Solution

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.

Problem

Subject. I want init a new instance of model in it static method: ``` var Schema = new mongoose.Schema({...}); //... Schema.statics.createInstance = function (name, pass) { var newPerson = new Person; // <--- or 'this', or 'Schema'? newPerson.name = name; newPerson.pass = pass; newPerson.save(); return newPerson; } // ... module.exports = db.model("Person", Schema); ``` How I can do this?

Original source