MongoDB and Mongoose - Create Many Records with model.create()

I am having a syntax error here. What can I be doing wrong?

I’ve also added

const Model = mongoose.Model;

on top of the myApp.js

var createManyPeople = function(arrayOfPeople, done) {
    Model.create(arrayOfPeople, (err, data) => {
      if(err) {
         done(err); 
      }
    done(null, data);
    }) 
};

https://learn.freecodecamp.org/apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model-create

2 Likes

I could be that should be mongoose.model instead of mongoose.Model.

Also, did you create a Schema?
I wrote first a Schema and then passed it to the model like mongoose.model(‘Person’, personSchema).
And then you use Person.create(…).

Here is a link to mongoose documentation for models.
http://mongoosejs.com/docs/models.html

4 Likes

Thanks I got it. Schema was already created as part of the previous solution. I thought I had to use literally Model.create instead of using an instance of model and associated create method.

Thanks!

2 Likes

var Model = mongoose.model;
var createManyPeople = function(arrayOfPeople, done) {
Model.create(arrayOfPeople, (err, data) => {
if(err) {
done(err);
}
done(null, data);
})
};

what is the wrong with my code.

Don’t use Mode.create.

Instead use the schema you already created in the previous exercise.

Which I remember is Person?..

var createManyPeople = function(arrayOfPeople, done) {
    Person.create(arrayOfPeople, function (err, data) {
      if (err) {
        done(err);
      }
    done(null, data);
    });
    
};
1 Like

var createManyPeople = function(arrayOfPeople, done) {
Person.create(arrayOfPeople, function (err, data) {
if (err) {
done(err);
}
done(null, data);
});

};

what is “data” here in this function i am not getting

done(null, data);

This worked for me. Can you explain why we didn’t need to use the .save method for the arrayOfPeople or does model.create automatically save?

1 Like

Hi @tmstani23,

It seems like Mongoose sets a clear separation when creating records for one user and many users.
Save is kept for one user while create is kept for many users.

In my understanding, I’m wondering if that is made to reduce errors from the developer’s side

On top of it, create wants you to pass the array of users together with the callback function while save only takes the callback function.

1 Like

I’ve passed challenges 3 and 4 of mongodb and mongoose but why they didn’t save any records in database?

var createManyPeople = function(arrayOfPeople, done) {
 
    Person.create( arrayOfPeople, (err, data) => err ? done(err) : done(null, data) );

  };