【发布时间】:2022-03-14 19:54:22
【问题描述】:
我有一个包含以下项目子模式的库存模式:
const ItemSchema = new mongoose.Schema(
{
name: { //Full name of product
type: String,
},
type: { //Beer? Wine? Liquor? Cider?
type: String,
},
unit: { //What is the minimum amount you can order?
type: Number,
},
volume: { //How much liquid is in it?(in mL)
type: Number,
},
packaging: {
type: String,
},
quantity: {
type: Number,
},
price: {
type: Number,
},
},
{
timestamps: true,
}
const InventorySchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: [true, 'Need user ID'],
ref: 'User'
},
items: {
type: [ItemSchema],
default: []
}
},
{
timestamps: true,
}
我正在构建一个 API 来添加子模式项,但我该怎么做?
const addItem = asyncHandler(async (req, res) => {
//req.user.id is given by authentication middleware
//req.body is the ItemSchema object
if (!req.user.id) {
res.status(400);
throw new Error('Cannot add without ID')
}
const newItem = {
user: req.user.id,
items: await ItemModel.create(req.body),
}
res.status(200).send(newItem)
这就是我的 ATM,但我认为我做得不对。我得到“无法读取未定义的属性(读取'创建')”响应。
【问题讨论】:
标签: database object mongoose post schema