这是我的Mongoose Schema:
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发布数据。
答案 0 :(得分:1)
获取发布数据
在mongoose中添加新记录
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'))
});
答案 1 :(得分:0)
批量添加商品
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