表单mongoose从POST中填充子文档数组

这是我的Mongoose模式:

const InvoiceSchema = new Schema({ name: { type: String, required: true }, description: { type: String }, items: [{ product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'}, amount: { type: Number }, name: { type: String, required: true }, quantity: { type: Number }, rate: { type: Number, required: true } }], createdBy: { type: Schema.ObjectId, ref: 'User', required: true }, } 

现在我想从POST数据填充我的模式,我的问题是我不知道如何发布我的项目(如何命名我的领域)?

我用PostMan发布Datas。

获取发布数据

在mongoose中添加新logging

 const {ObjectId} = mongoose.Schema.Types; const newInvoice = new InvoiceSchema({ name: "John Smith", description: "This is a description", items: [{ product: 'THIS_IS_AN_OBJECT_ID_STRINGIFIED', amount: 2, quantity: 5, //name - comes from the product model //rate - comes from the product model }] }); newInvoice.save(); 

发布并保存

 //Response format { name: 'John Smith', description: 'This is a description', items: [ { product: 'THIS_IS_AN_OBJECT_ID', amount: 2, quantity: 5 } ] } app.post('/yourRoute', (req, res) => { const {name, description, items} = req.body; const newInvoice = new InvoiceSchema({name, description, items}); newInvoice.save().then(()=>res.send('success')) }); 

批量添加项目

 const invoice = new Invoice(); invoice.items = req.body.items; 

添加单个项目

 invoice.items.push(item); 

更新单个项目

 const item = invoice.items.id(req.params._id); item.attribute = ... // Do update