Mongoose Create/Save Record Challenge - Test passed, record is not saved / Test fails, record is saved

I am doing the Mongoose challenges, and now I’m experimenting a weird situation regarding the Save a Record of a Model challenge.

The connection and the Schema and Model creations processes are both okay. The problem start when I try to create and save a record to the BD. When I try this using the done() function, the test passes, but, when I check the BD used for connection in mLab, the record is not saved in the DB.

Here is my code, up to that challenge:

/* Mongoose Set Up */
var mongoose = require("mongoose");   
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser:true});

/* Schema and Model creation */ 
var personSchema = new mongoose.Schema({
  name: {
      type: String,
      required:true
  },
  age: Number,
  favoriteFoods: Array 
});

/* Create and save a Record */
var createAndSavePerson = function(done) {
    var person = new Person({name:"John",
                      age:30,
                      favoriteFoods:['Salmon', 'Sushi']}); 

    person.save(function(error,data){
        if (error) 
            return done(error); 
        done(null, data); 
    }); 
};

All this challenges ask me to use the done() function. The even weirder thing, is that when I decide not to use the done() function (which is not supposed to), the test fails due to a Timeout, but the record is saved in the DB.

/* Create and save a Record */
var createAndSavePerson = function(done) {

    var person = new Person({name:"John",
                      age:30,
                      favoriteFoods:['Salmon', 'Sushi']}); 

    person.save(function(error,data){
        if (error) 
            console.log(error); 
        console.log(data + " saved to the DB"); 
    }); 
};

Link to the challenge:

In your if statement don’t use “return”.

Just call the done function.

If it’s for the code with the done() function, removing the return statement doesn’t change anything. The test passes, but the record is still not being saved.

In the code without the done() function, I re-checked and edited the code, because the return statement was not necessary.

The challenges is to build a model file of some prebuilt methods, you can see there are several export statements in the end of the file, they were to required and used in another file. Thus, those functions you build is statements, and not invoked yet.

2 Likes