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
What am I doing wrong?
How to save the data correctly?
