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?
Each Schema can define instance and static methods for its model.
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.
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') .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With