Cannot read property 'modelName' of undefined

Cannot read property 'modelName' of undefined
0
#1

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

#2

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!

#3

@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);

#4

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!

#5

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?

#6

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!

#7

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: