Cannot read property 'modelName' of undefined

MongoDB and Mongoose - Create and Save a Record of a Model

i AM GETTing this error in this challenge . i am not able to clear the test.

var personSchema= new mongoose.Schema(
 {
    name:{ 
           type:String,
           required:true
    },
    age:Number,
   favoriteFoods:[String]
   
 
 })
 
 var Person = mongoose.model('Person',personSchema); 

var createAndSavePerson = function(done) {
  
  var Mr = new Person({name:'Silence',age:25,favoriteFoods:"Bread"});
console.log(Mr.name);
  
  Mr.save(function(err, data) {
  console.log("hello");
});
          
  
  done(null, Mr);
  
  
}

i have ceated and saved but still its showing same please consider this

I am having this issue as well and could not find anything helpful on the forum so far.
Could someone plz take a look at my codes:


Thanks!

@rabi-999 when you are creating Mr you are setting favoriteFoods to a String (you should set it to an Array).

The other thing. I would handle an error in your place like so:

  Mr.save(function(err, data) {
  console.log("hello");
  err ? done(err) : done(null, data);
});

and I would delete done(null, Mr);

Hi @orvalho, I tried to follow your hints and this is what I have so far:

Could you please kindly point out which part is wrong? Thanks!

Take a look at your code:

var createAndSavePerson = function(done) {
  var ap = new Person({name: "John", 
                       age: 30, 
                       favoriteFoods: ["apple", "milk"]});
  
  //ap.save();
  ap.save(function(err, ap) {
    console.log("hello");
    err ? done(err) :  done(null, data);
  });
  //done(null /*, data*/);

//};

The function createAndSavePerson needs a closing curly brace. So, commenting it out is probably not a good idea. Also, for your callback function output done(null, data), where have you defined data previously?

Hi @willjw3, I probably haven’t defined the data anywhere. Actually I don’t know how this part:

ap.save(function(err, ap) {
    console.log("hello");
    err ? done(err) :  done(null, data);
  });

works at all - I am just mimicking others’ solution that I can find on this forum.
I don’t have any Node.js background but just jumped into the FCC challenges. Do you have any recourse (books/online tutorial etc.) to recommend so that I can grasp some fundamental stuff of node.js? Thanks!

In

ap.save(function(err, ap) {
  // ...
  err ? done(err) : done(null, data);
});

The value ap that you’ve passed into your callback function could be used instead of data in done(null, data) for example.
One of the best online instructors in my opinion is Max at Academind. Here’s his video tutorial on Node.js:

1 Like