简体   繁体   中英

No recursive function, still getting a Maximum call stack size exceeded error

I'm experimenting with Node, Express and Mongoose. Here's part of my model -- book-model.js which exports its schema and methods for use in a controller. I'm implementing the fat model, skinny controller approach:

// ...

BookSchema.statics.create = function(title, author, category, callback) {
    var Book = mongoose.model('Book');
    Book.create({
        title: title,
        author: author,
        category: category
    }, callback);
};

// ...

module.exports = mongoose.model('Book', BookSchema);

And here's part of the controller -- books-controller.js :

// ...

var Book = require('./book-model');

router.post('/', function(req, res) {
    var title = req.body.title,
        author = req.body.author,
        category = req.body.category;
    Book.create(title, author, category, function(err) {
        if (err) {
            console.log(err);
            res.redirect('/add-book');
        }
        res.redirect('/books');
    });
});

// ...

Now, when I attempt to create a new book document, I get the annoying Maximum call stack size exceeded message. I had a look at a similar question here on SO: Maximum call stack size exceeded error and the answer is that "Somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. This is almost always because of a recursive function with a base case that isn't being met."

I can't see a recursive function in the books-controller.js file that has a base case that isn't being met or what is it that I'm missing?

Please advise.

Here's your recursion:

BookSchema.statics.create = function(title, author, category, callback) {
    var Book = mongoose.model('Book');
    Book.create({
        title: title,
        author: author,
        category: category
    }, callback);
};

Basically, you're declaring a Book.create method that calls Book.create . Since javascript doesn't have operator overloading, it doesn't realize that your redefinition conflicts with the older Book.create that takes only two arguments.

Rename the function to something else like make to break the recursion:

BookSchema.statics.make = function...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM