I've been having a problem with saving data from an array object to the MongoDB database. I have my schema for the main document with embedded subdocuments. The saves for the main document and all the other subdocuments were successful except for a subdocument which is an array.
As you can see from the screenshot, the fields from the subdocuments are not being saved to the database.
Any help would be much appreciated. Thanks!
Sample request object:
{
"incidentNumber": "IN1001",
"status": "New"
"Approval": {
"approvers": [
{
"approverType": "Asset Management",
"approverName": "Bob",
"approvalDate": 1234
},
{
"approverType": "HR",
"approverName": "Janet",
"approvalDate": 1234
},
{
"approverType": "Finance",
"approverName": "Bill",
"approvalDate": 1234
}
]
}
}
Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const approvalSchema = new Schema(
{
approvers: [
{
approverType: {
type: String
},
approverName: {
type: String
},
approvalDate: {
type: Date
}
}
]
}
);
const headerSchema = new Schema(
{
incidentNumber: {
type: String,
required: true,
unique: true
},
status: {
type: String,
required: true,
enum: ['Completed', 'Draft', 'New', 'Pending', 'Submitted']
},
approval: [approvalSchema]
},
{ timestamps: true }
);
Server code:
let incidentNumber: "IN1001";
let status: "New";
app.post('/create-incident', (req, res) => {
const header = new Header({
incidentNumber: incidentNumber,
status: status,
approval: [
{
approvers: [
{
approverType: req.body.Approval.approvers.approverType,
approverName: req.body.Approval.approvers.approverName,
approvalDate: req.body.Approval.approvers.approvalDate
}
]
}
]
});
});
header
.save()
.then(Header => {
res.status(200).send(Header);
})
.catch(e => {
res.status(400).send(e);
}