Node.js 将回调传递给其他文件中的函数
我正在处理一个平均堆栈项目,在我的服务器模型中,我使用了以下mongoose钩子:Node.js 将回调传递给其他文件中的函数,node.js,mongoose,Node.js,Mongoose,我正在处理一个平均堆栈项目,在我的服务器模型中,我使用了以下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
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()之类的东西
谢谢你的帮助。谢谢大家! 这只是意味着,您没有按照Mongoose的要求将next()回调传递给.pre()中间件函数 next()是必需的,这样mongoose就知道中间件何时完成了它的工作,并跳到队列中的下一个 因为如果作为参数传递,preSave()函数已经调用了next(),所以只需要像这样传递next()
userSchema.pre('save', function(next){
console.log('I am the extra work')
theFile.preSave(next)
})
userSchema.pre('save', function(next){
console.log('I am the extra work')
theFile.preSave(next)
})