Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 411
Dmitry Avatar asked Dec 24 '12 07:12

Dmitry


People also ask

Can you define methods in a Mongoose schema?

Each Schema can define instance and static methods for its model.

What is schema and model in Mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

How do you add a static function to a Mongoose model?

Hooks for Custom Statics Statics are Mongoose's implementation of OOP static functions. You add a static function to your schema, and Mongoose attaches it to any model you compile with that schema. Mongoose 5.5 introduces the ability to add hooks for custom statics, like schema. pre('findByName') .

What is instance method in Mongoose?

methods are defined on the document (instance). You might use a static method like Animal.findByName : const fido = await Animal. findByName('fido'); // fido => { name: 'fido', type: 'dog' } And you might use an instance method like fido.findSimilarTypes : const dogs = await fido.


1 Answers

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.

like image 110
JohnnyHK Avatar answered Oct 10 '22 08:10

JohnnyHK