我一直遇到将数据从数组对象保存到MongoDB数据库的问题。我有主要文档的架构与嵌入的子文档。除了作为数组的子文档之外,主文档和所有其他子文档的保存都是成功的。
从截图中可以看出,子文档中的字段未保存到数据库中。
非常感谢任何帮助。谢谢!
示例请求对象:
{
"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
}
]
}
}
架构:
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 }
);
服务器代码:
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);
}