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…