Update: I know the problem now. This is the follow-up question.
I'm working with a MMEAN stack with Mongoose and MongoDB. I'm getting a TypeError: undefined is not a function
error on the save()
because I'm trying to save to MongoDB with Mongoose inside a callback. I don't know how to save it properly.
This is the logic I must follow:
- check if the Foo collection is empty
- If Foo is empty, save the new Foo document
- If Foo is not empty, do not save the new Foo document
I believe the rest of the code except for the problematic mongoose.model("Foo").save(cb);
line is error-free. But just in case, I've included everything here. I'm calling the save method, addFoo()
, from routes/index.js.
// routes/index.js - No errors here
router.post('/foo', function(req, res, next){
var foo = new Foo(req.body);
foo.addFoo(function(err, bid){
if(err){ return next(err); }
res.json(foo);
});
});
// models/Foo.js - THE ERROR IS IN HERE
var mongoose = require('mongoose');
var FooSchema = new mongoose.Schema({
creator: String
});
mongoose.model('Foo', FooSchema);
FooSchema.methods.addFoo = function(cb){
// finds all documents of Foo into the "results" array
this.model("Foo").find(function(err, results){
if (err){return err;}
// if the Foo results array is empty
if (results.length == 0){
// THE LINE BELOW IS WHERE THE ERROR OCCURS
// mongoose.model("Foo").save(cb);
// ^
// TypeError: undefined is not a function
mongoose.model("Foo").save(cb);
return;
}
});
}
Thanks for helping me debug.