最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js Mongoose static function not getting called - Stack Overflow

programmeradmin10浏览0评论

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;

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;
Share Improve this question edited Jan 20, 2015 at 13:00 asked Jan 20, 2015 at 11:39 anonanon 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? – Rodrigo Medeiros 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. – anon 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. – Rodrigo Medeiros 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. – anon 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? – Rodrigo Medeiros Commented Jan 20, 2015 at 12:51
 |  Show 1 more ment

1 Answer 1

Reset to default 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
});
发布评论

评论列表(0)

  1. 暂无评论