【问题标题】:POST to mongoose DB with Nested schema使用嵌套模式 POST 到 mongoose DB
【发布时间】: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


    【解决方案1】:

    首先, 创建模式时,如果你只有一个常规类型,只需编写类型,不需要所有开销-

    const ItemSchema = new mongoose.Schema({
     name: String,
     type: {type: String},
     unit: Number... etc..
    }
    

    另外,数组默认值是空数组,所以你不需要告诉猫鼬。所以你可以在你的 InventorySchema 中做:

    items:[ItemSchema]
    

    关于你的问题, 首先,您需要从模式中创建模型。 比如:

    const InventoryModel = new mongoose.model('Inventory', InventorySchema);
    

    并且对项目架构也这样做

    然后从中创建一个新项目,并在您的控制器中:

    ...
    ...
    const newItem = new ItemModel({....});
    const newInventory = new InventoryModel({user: req.user.id,});
    newInventory.items.push(newItem);
    newInventory.save(); 
    ...
    ...
    

    新的库存会保存在您的数据库中,您可以随心所欲地使用它

    【讨论】:

    • 感谢您的帮助!但是如果我尝试使用现有的 objectID 推送一个 newItem(所以该项目已经在项目中),会发生什么?理想情况下,我希望它更新现有对象而不是添加新对象。我是否需要在找到匹配的 _id 时遍历对象和 POST,还是数据库会为我做这件事?
    • @Steve 我希望我能正确理解您的问题 - 您创建了嵌入了 items 属性的 InventorySchema!并且不像用户属性(由objectId)那样引用,因为它是嵌入的,它存在于文档中。这就是为什么在示例中我创建了一个新项目并推送它。我没有寻找现有的并推动它们。如果你愿意,你可以通过引用而不是推送现有项目的 _id 来实现。对不起,如果我没有正确理解你,请尝试再次解释自己
    猜你喜欢
    • 2017-07-06
    • 2015-03-29
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多