首页 > 解决方案 > 如何在 mongodb (mongoose) 中实现食谱

问题描述

我想创建一个基于具有猫鼬数据库背景的 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.jsapimongoosemongoose-schema

解决方案


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

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}
    }],

推荐阅读