如何在同一模型的模式方法中创建模型实例?

时间:2021-02-02 02:36:47

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?

我怎么能这样做?

2 个解决方案

#1


26  

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方法中注册的模型,因此您的代码应更改为:

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.

Leonid对于处理保存回调是正确的,即使它只是为了记录错误。

#2


1  

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:

你几乎回答了你的问题。您的代码唯一的问题是此时您没有注册模型。但您可以使用mongoose.model动态获取它:

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.

噢。并考虑处理保存回调。您无法确定保存操作是否会失败。

#1


26  

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方法中注册的模型,因此您的代码应更改为:

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.

Leonid对于处理保存回调是正确的,即使它只是为了记录错误。

#2


1  

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:

你几乎回答了你的问题。您的代码唯一的问题是此时您没有注册模型。但您可以使用mongoose.model动态获取它:

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.

噢。并考虑处理保存回调。您无法确定保存操作是否会失败。