我想包裹 Mongoose Model.create我自己的方法 static创建方法:
// File: Task.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = mongoose.Schema({
name: String
});
// Custom static create method
taskSchema.statics.create = function (task) {
console.log('CREATING TASK');
return this.model('Task').create(task); // should call Mongoose `create`, not my custom static.
};
module.exports = mongoose.model('Task', taskSchema);
使用方法如下:
// Usage:
var Task = require('Task.js');
var promise = Task.create(taskObject); // call custom static `create`.
但这行不通。在返回 RangeError:超出最大调用堆栈大小
之前,它会多次记录CREATING TASK
。
我怀疑 this.model('Task').create(task)
调用我的自定义静态 create
方法而不是 mongoose create
方法,从而导致无限循环。例如,如果我将自定义方法重命名为 myCreate
,一切都会按预期工作。
我怎样才能仍然拥有我的 create
方法,但在其中调用 mongoose create
?
最佳答案
您应该能够使用 Function.prototype.call()
来使用您需要的模型调用 Model.create()
函数:
taskSchema.statics.create = function (task) {
console.log('CREATING TASK');
return mongoose.Model.create.call(this.model('Task'), task);
};
因此,这将调用 mongoose.Model.create(task)
并将函数调用的“this”设置为 this.model('Task')
。
关于javascript - 将 Model.create 包装在自定义静态创建中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21391459/