0

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:

  1. check if the Foo collection is empty
  2. If Foo is empty, save the new Foo document
  3. 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.

Community
  • 1
  • 1
Melissa
  • 1,236
  • 5
  • 12
  • 29

1 Answers1

1

It's wrong to write mongoose.model("Foo").save(cb).

You need a valid model to work with Your defined schema "Foo", var Foo = new mongoose.model('Foo', FooSchema).

Then you need to create an instance of the model Foo like that var test = new Foo({creator:'test'}) and only after that you will be able to call .save() on the instance test.

John Davis
  • 172
  • 1
  • 19
  • Is there a way to pass the result.length == 0 as a boolean out into the addFoo function? – Melissa Oct 13 '15 at 23:41
  • I have a follow-up question for my previous comment, please check it out: http://stackoverflow.com/q/33114479/4825465 – Melissa Oct 13 '15 at 23:55