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

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

#1

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;

mongoose.connect(process.env.MONGO_URI);
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”]})
createAndSavePerson.save(function(err, data) {
createAndSavePerson.done(data);
});


#2

try favoriteFoods instead of favouriteFoods.


#3

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:

// person.save(function(err, data) {
//    ...do your stuff here...
// });

You should nest the second code snippet inside the first.


#4

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


#5

And also thank you @shimphillip.


#6

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…


#7

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.