1

Recently i've been trying to rewrite my node.js express app to be more in line with the mvc principle. I've also been trying to incorporate mongoose. I'm having a problem with calling the static functions on a mongoose model.

userSchema.statics.findDuplicates = function (cb) {
    console.log("Duplicates called");

    this.findOne({ email: this.email }, function(err, result){
        if (err) throw err;
        if (result) {
            cb("A user with this email has already been created.");
        } else {
            cb("");
        }
    });
}

Now the problem is that i'm later exporting a model using this schema, so this is all contained in one file:

module.exports = mongoose.model('User', userSchema);

When i later call this inside a controller, (obviously requiring and initiating the model beforehand):

user.findDuplicates(function(result){

    if (result) {
        res.send("Selle e-mailiga kasutaja on juba loodud.");
        console.log("Duplicates");
    } else {
        user.save();
        res.send("Kasutaja loodud.");
        console.log("User created with password.")
    }
});

It just never gets called. Node tells me it accepted a post, but got a 500 internal server error, and the "Duplicates called" inside findDuplicates does not appear in the console. Something is very wrong here, and i do not know how to fix it.

EDIT: Full controller code:

var express = require('express');
var router = express.Router();

var User = require("../models/user.js");

router.get('/', function(req, res, next) {
    res.render('users',{title: "Lisa kasutaja"});
});

router.post('/', function(req, res, next) {
    var query = req.body;
    var message = "";

    console.log("Post recieved " + JSON.stringify(query));

    if (query.password != query.repeatPassword){
        res.send("Paroolid ei ole võrdsed.");
        console.log("Passwords don't match");
    } else {
        var user = new User({
            firstName: query.firstName,
            lastName: query.lastName,
            telephone: query.telephone,
            email: query.email,
            password: query.password
        });

        console.log("User created");

        user.findDuplicates(function(result){

            if (result) {
                res.send("Selle e-mailiga kasutaja on juba loodud.");
                console.log("Duplicates");
             } else {
                user.save();
                res.send("Kasutaja loodud.");
                console.log("User created with password.")
            }
        });
    }

});

module.exports = router;
6
  • I'm quite sure you're getting an error before the user.findDuplicates call. Other than your 500 internal server error, do you have anything else in the error stack? Commented Jan 20, 2015 at 11:55
  • No, does not seem like i do. Also just before that call in the controller (after initalizing the new User) it logs that it successfully created the user. Breaks just after that. Commented Jan 20, 2015 at 12:01
  • This user object is the model exported from mongoose.model('User', userSchema) or is a doc returned from a mongoose query to the database? If the latter is true, you should use an instance method. Commented Jan 20, 2015 at 12:30
  • It's the model that i exported. In the controller i create a new user, and use static functions and methods defined in the model to check for duplicates and hash + salt everything before i save it to the database. Commented Jan 20, 2015 at 12:41
  • Ok. Could you please update your question with the code from the controller method where you call user.findDuplicates? Commented Jan 20, 2015 at 12:51

1 Answer 1

8

Your problem resides in the fact that you're calling a static method in an instance of a model, which is not correct. See the difference below:

// if you define a static method
userSchema.statics.findDuplicates = function (cb) {
  // do your stuff
}

// you call it this way
var User = require("../models/user.js");
User.findDuplicates(function (result) {
  // do your stuff
});

// if you define an instance method
userSchema.methods.findDuplicates = function (cb) {
  // do your stuff
};

// you call it this way (on an instance of your model)
var User = require("../models/user.js");
var user = new User({
      firstName: query.firstName,
      lastName: query.lastName,
      telephone: query.telephone,
      email: query.email,
      password: query.password
    });
user.findDuplicates(function (result) {
  // do your stuff
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.