这是我的猫态架构:
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 },
}
现在我想从帖子数据填充我的模式,我的问题是我不知道如何发布我的物品(我如何命名我的字段(??
我用邮递员发布数据。
获取发布数据
添加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'))
});
批量添加项目
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