本文介绍了如何在同一模型的架构方法中创建模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主题.我想在它的静态方法中初始化模型的新实例:

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);

我该怎么做?

推荐答案

您在正确的轨道上; this是架构在schema.statics方法中注册的模型,因此您的代码应更改为:

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;
}

列昂尼德(Leonid)关于处理save回调是正确的,即使只是记录错误也是如此.

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

这篇关于如何在同一模型的架构方法中创建模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 09:21