user2915962 user2915962 - 3 months ago 14x
Node.js Question

Pass callback to function in other file

Im working on a MEAN-stack project and in my model on the server i use the following mongoose hook:

File: user.server.controller.js

exports.preSave = function(next) {
this.wasNew = this.isNew;
console.log('I got called from another file..')

Now i am exporting the above file and require it in a file where i have created my user model.

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;

The above code works and will log 'I got called from another file'.

Now, what I need to do is to carry out some extra work in this function:

userSchema.pre('save', theFile.preSave)

My first attempt looks something like this:

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

This results in an error regarding the middleware:

Throw new Error('You pre must have a next argument --e.g., function (next ...)')

I think that i might lack in knowledege regarding passing functions as parameters in the proper way. Is this maybe a situation where I should use something like apply() or bind() somehow?

Help appreciated. Thank you!


This just means, you're not passing a next() callback to the .pre() middleware function as required by Mongoose.


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

next() is needed so mongoose knows when the middleware is done with it's thing and jump to the next one in line.

Since your preSave() function already calls next() if passed as an argument, you just need to pass next() to it like this

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