【问题标题】:mongoose schema not sending correct address details猫鼬模式未发送正确的地址详细信息
【发布时间】:2022-01-15 08:03:46
【问题描述】:

想知道是否有人知道我如何为以下模型开发架构,所有字段都是必需的。

我想要捕获的数据 { “名称”:“商店”, “地址”: { "line_one":"乔博客大道 123 号", "line_two":"1区",
"city":"随机城市", "邮编/邮编":"AB12 3BJ" }, "coverImage":"imageURL", “评分”:4.5 }

    const placeSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    address: {
      line_one: {
        type: String,
        required: true,
      },
      line_two: {
        type: String,
        required: true,
      },
      city: {
        type: String,
        required: true,
      },
      postcode: {
        type: String,
        required: true,
      },
    },
  },
  coverImage: {
    type: String,
    rating: {
      type: mongoose.Types.Decimal128,
    },
  },
});

在发布数据时,我只发现返回了名称、封面图片、_id 和 __v。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    您可以为此使用子文档或嵌套模式: 所以基本上对于嵌套对象,你定义另一个模式,然后告诉主模式该字段的类型是子模式

    const addressSchema = mongoose.Schema({
        line_one: {
            type: String,
            required: true,
        },
        line_two: {
            type: String,
            required: true,
        },
        city: {
            type: String,
            required: true,
        },
        postcode: {
            type: String,
            required: true,
        }
    })
    
    const placeSchema = mongoose.Schema({
        name: {
            type: String,
            required: true,
            address: {
                type: addressSchema,
                required: true
            }
        },
        coverImage: {
            type: String,
            rating: {
                type: mongoose.Types.Decimal128,
            },
        },
    });
    ```
    

    【讨论】:

    • 谢谢马克斯!会试一试的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多