【问题标题】:Mongoose Object Array won't work on PostmanMongoose 对象数组不适用于 Postman
【发布时间】:2019-09-06 03:58:48
【问题描述】:

完成 MEAN Stack 课程后,我正在制作自己的 web 应用程序 - 一个食谱页面。我已经设计了我的模型,但是当我尝试用新配方填充数据库时,它就不起作用了。主要问题是我想要存储成分的方式,它们将存储在其中一张桌子上,然后每个食谱都有其成分列表和每种成分的数量。例如,要制作您需要的吐司,请说“50 克黄油和 4 片面包”。这是我正在使用的架构:

var RecipeSchema = Schema({
    name: String,
    desc: String,
    author: { type: Schema.ObjectId, ref: 'User' },
    category: { type: Schema.ObjectId, ref: 'Category' },
    ingredients: [{ amount: String, ingredient: { type: Schema.ObjectId, ref: 'Ingredient' }}],
    steps: [String],
    image: String,
    thumbnail: String,
    portions: Number,
    difficulty: Number,
    cookingTime: Number,
    comment: String
});

当我进入 Postman 并尝试填写“吐司食谱”条目时,我有以下内容:

name:Toast
desc:Toast is a common breakfast staple.
author:5cad791a7b2e651f7803f5de
category:5cb1ff8f484a172984178a97
ingredients:[{"amount": "4 slices", "ingredient": "5cb1ffdb484a172984178a98"}, {"amount": "35 grs.", "ingredient": "5cb2000d484a172984178a99"}]
steps:['Toast the bread in the oven.','Spread some butter on each toast.']
image:'null'
thumbnail:'null'
portions:1
difficulty:1
cookingTime:15
comment:'null'

但我不断收到“cast Array”错误。可能是什么问题?是我的模型、Postman 还是我发送数组的方式有问题?

编辑:

显然,我在 Postman 中发布数组的方式存在问题。经过更多测试后,我设法以 JSON 格式上传了完整的食谱。结构是正确的(但也可以使用 Juan 建议的,以使代码更清晰)。

【问题讨论】:

    标签: mongodb mongoose postman


    【解决方案1】:

    我不完全确定,但是当我使用猫鼬时,内部对象内部有一个新的 Schema 对象,在这种情况下它会在成分上

    const IngredientSchema = new Schema({ 
        amount: String, 
        ingredient: { type: Schema.ObjectId, ref:'Ingredient' }
    });
    
    const RecipeSchema = new Schema({
        name: String,
        desc: String,
        author: { type: Schema.ObjectId, ref: 'User' },
        category: { type: Schema.ObjectId, ref: 'Category' },
        ingredients: [ IngredientSchema ],
        steps: [String],
        image: String,
        thumbnail: String,
        portions: Number,
        difficulty: Number,
        cookingTime: Number,
        comment: String
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-20
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 2021-10-18
      • 2012-07-29
      相关资源
      最近更新 更多