2

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?

1
  • probably, it's somehow relevand with the _id field (and it's generation) for embed docs inside the array. Mongoose won't return you an error, because the doc is saved successfully. Also, you may find useful this answer about ar of mine, if you will try to work and update the array field via .save() method in the future. Commented Mar 19, 2021 at 17:38

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I get an error ModuleModel.insert is not a function
never mind, works now. used "insertMany" instead of "insert". any specific reason for using "insert" in your answer?
Hey maX, pardon, this was a mistake, and fixing the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.