【发布时间】:2016-06-26 15:30:15
【问题描述】:
我正在处理一个 MEAN-stack 项目,在我的服务器模型中,我使用以下 mongoose 钩子:
File: user.server.controller.js
exports.preSave = function(next) {
this.wasNew = this.isNew;
console.log('I got called from another file..')
next();
}
.....
现在我正在导出上述文件,并在我创建了我的用户模型的文件中要求它。
File: user.server.model.js
var theFile = require('Path to the file above')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
});
var User = mongoose.model('User', userSchema);
//Here i can use the "hook":
userSchema.pre('save', theFile.preSave)
module.exports = User;
上面的代码有效,并且会记录“我从另一个文件中被调用”。
现在,我需要在这个函数中进行一些额外的工作:
userSchema.pre('save', theFile.preSave)
我的第一次尝试看起来像这样:
userSchema.pre('save', function(){
console.log('I am the extra work')
theFile.preSave
})
这会导致中间件出错:
Throw new Error('You pre must have a next argument --e.g., function (next ...)')
我认为我可能缺乏以正确方式将函数作为参数传递的知识。这可能是我应该以某种方式使用 apply() 或 bind() 之类的情况吗?
帮助表示赞赏。谢谢!
【问题讨论】: