【问题标题】:How to implement recipes in mongodb (mongoose)如何在 mongodb (mongoose) 中实现食谱
【发布时间】:2020-08-01 23:36:33
【问题描述】:

我想创建一个基于具有猫鼬数据库背景的 nodejs 服务器的鸡尾酒 API。 API 将返回带有配方的鸡尾酒 我有一个包含鸡尾酒、用户和配料的工作原型。 我的问题是如何实现成分的数量?如果我例如。想要使用 2cl 的成分或 1 汤匙,我将如何在我的方案中实现这一点?

鸡尾酒模式

const schema = new Schema({
    name: { type: String, required: true },
    recipe: {type: String, required: true },
    ingredients: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Ingredient'
    }],
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    createdDate: { type: Date, default: Date.now }
});

用户模式

const schema = new Schema({
    username: { type: String, unique: true, required: true },
    hash: { type: String, required: true },
    email: { type: String, required: true },
    favoriteCocktails:[{
        type: Schema.Types.ObjectId,
        ref: "Cocktail"
    }],
    createdDate: { type: Date, default: Date.now }
});

成分模式

const schema = new Schema({
    name: { type: String, required: true },
    alcoholic: { type: Boolean, required: true },
    description: {type: String, required: false},
    createdDate: { type: Date, default: Date.now }
});

我正在考虑在成分变量的鸡尾酒模式中添加一个字符串。我将如何实现这一点? 非常欢迎任何有关如何执行此操作或改进此操作的帮助提示

【问题讨论】:

    标签: node.js api mongoose mongoose-schema


    【解决方案1】:

    要为您的成分实施数量,请查看成分的架构。

    const schema = new Schema({
        name: { type: String, required: true },
        alcoholic: { type: Boolean, required: true },
        description: {type: String, required: false},
        createdDate: { type: Date, default: Date.now }
    });
    

    您已经拥有名称、描述、酒精、创建日期等信息。通过添加数量字段,例如quantity: {type: String, required: false},,您可以输入所需的信息。或者,如果您想将数量作为整数,您可以有两个字段:一个用于数量(5),一个用于数量类型(汤匙)

    编辑

    为了减少配料模型的数量,您可以在放入配料时将信息添加到鸡尾酒模式的嵌套位置。像这样(在鸡尾酒模式下):

    ingredients: [{
            ingredient: {type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient'}
            quantity: {type: Number, required: false},
            quantityType: {type: String, required: false}
        }],
    

    【讨论】:

    • 用这个例子,不会有很多同名的成分吗?在一个食谱中,一个人会使用 2cl 的伏特加,在另一个 4cl 中。那么会有 2 种伏特加成分?
    • 有效;我更新了我对另一种可能的解决方案的回复,该解决方案考虑到了这一点@JefVandooren
    • 这看起来像是我需要的答案!如果我要使用它,我是否也需要更新成分方案?
    • 不,您的成分架构应该能够保持不变。您只需要更改将数据输入到鸡尾酒模式中的方式 :)
    • 谢谢!真的帮了大忙!
    猜你喜欢
    • 2016-09-22
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多