【问题标题】:Pass callback to function in other file将回调传递给其他文件中的函数
【发布时间】: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() 之类的情况吗?

帮助表示赞赏。谢谢!

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    这只是意味着,您没有按照 Mongoose 的要求将 next() 回调传递给 .pre() 中间件函数。

    Docs

    userSchema.pre('save', function(next){
     console.log('I am the extra work')
     theFile.preSave()
     next()
    })
    

    next() 是必需的,所以猫鼬知道中间件何时完成它的事情并跳转到下一个。

    由于您的 preSave() 函数已经调用 next() 如果作为参数传递,您只需像这样将 next() 传递给它

    userSchema.pre('save', function(next){
     console.log('I am the extra work')
     theFile.preSave(next)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2013-02-15
      • 2012-03-07
      • 1970-01-01
      相关资源
      最近更新 更多