maX
maX

Reputation: 742

mongoose - trying to save an array of documents, only empty array saved

I have a schema defined like this

var PersonelModelSchema = new Schema({
  emailAddress: String,
  fullName: String
});

var ModuleModelSchema = new Schema({
  modName: String,
  personels:[PersonelModelSchema ]
});


var ModulesModelSchema=new Schema({
  modules: [ModuleModelSchema ]
});

var ModulesModel = mongoose.model('ModulesModel ', ModulesModelSchema );

This schema is used to save data sent by another app to an api end point built on nodejs

The json data contains an array, the contents of which I want to save as separate documents - ie is the array has 2 objects, each needs to be saved as separate documents. This is the reason I am using array if ModuleModelSchema, so that I can get all the objects in array.

The data that is posted is looks like this

{"modfulldata" :[{
  "modName": "example-45435q5",
  personels: [
    {
      "emailAddress": "name@example",
      "fullName": "name"
    },
    {
      "emailAddress": "name2@example",
      "fullName": "name2"
    }
  ]
},
{
  "modName": "example-f45b",
  personels: [
    {
      "emailAddress": "name3@example",
      "fullName": "name3"
    },
    {
      "emailAddress": "name4@example",
      "fullName": "name4"
    }
  
  ]
}
]}

And this is the code I am using to save

app.post('/savemd', 
    function(req,res){
        console.log(req.body.modfulldata);// the data is shown correctly here

        mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true });
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function callback () {
            console.log("open");          

        });

        var newmods=new ModulesModel (req.body.modfulldata);
        
    ModulesModel.insertMany(newmods).then(function(){
                db.close();
        });

    });

There are no errors thrown. With the console.log statement, i can see the request json data is read correctly. However in mongodb, there is only an empty array in the saved document

mongodb result

What am I doing wrong?

How to save the data correctly?

Upvotes: 2

Views: 1205

Answers (1)

dhruv479
dhruv479

Reputation: 321

The issue here is the body.modfulldata is an array and you simply can not create mongoose schema object like this, instead iterate the array and generate mongoose schema object and then insert them. Example:

const newmods = req.body.modfulldata.map(dataObj => {
                  return new ModulesModel(dataObj);
                });
await ModuleModel.insertMany(newmods);

Upvotes: 3

Related Questions