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

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


I have been working on this for three days and I still don’t know what is wrong with this!Please Help!
My code:
const mongoose = require(‘mongoose’);
const mongoDB = require(‘mongodb’);
const Schema = mongoose.Schema;

var personSchema = new Schema({
name: String,
age: Number,
favouriteFoods: [String]


const Person = mongoose.model(‘Person’, personSchema)

var createAndSavePerson = new Person({name: “Ben”, age: 23, favouriteFoods: [“tuna”, “bread”]}), data) {


try favoriteFoods instead of favouriteFoods.


The done function is not a property of createAndSavePerson. It works by itself and takes up to two arguments. The first is an error object (if any), the second will be the data returned from the mongoose function (if any).

Also, your code doesn’t follow the structure required as provided by the comments.

Look again at this hint:

// - Example -
// var someFunc = function(done) {
//   ... do something (risky) ...
//   if(error) return done(error);
//   done(null, result);
// };

…And this one:

//, data) {
// your stuff here...
// });

You should nest the second code snippet inside the first.


Thank you @joops75.I thought it was really hard.


And also thank you @shimphillip.


Hi @joops75,
Thanks for your reply.
I just don’t get where the actual ‘done’ function is defined in the code.
Is it a NodeJS or Mongoose built-in function ?
Thanks forward for your help as I’m really puzzled by this one too…


The done function is provided by the server.js file (line 82 for the above example) and is for testing purposes only. It is needed because saving a record in a database is asynchronous (i.e. takes some amount of time), and calling it after the database operation is completed lets the test script know it should continue.

Most of the time the done function is not required when writing database code. However, if you use Passport.js or write test suites with Mocha.js then you will need to make use it. Fortunatley FCC covers those topics too.