【问题标题】:Why the structure of mongoose subdocument can be different?为什么猫鼬子文档的结构可以不同?
【发布时间】:2020-07-02 20:54:53
【问题描述】:

这是猫鼬的预期行为,还是不应该是这样。所以我有 2 个用户和地址架构。架构如下所示:

const addressSchema = {
  addressLine: { type: String},
  city: { type: String},
  locations: { type: String, coordinates: [Number] }, <-- subdocument
}

const userSchema = {
  name: { type: String },
  email: { type: String },
  addresses: {
    primary: { type: AddressSchema },
    others: { type: [AddressSchema] }
  }
}

我尝试插入这些数据:

{
   name: "John Doe",
   addresses: {
     primary: {
       addressLine: "Apple Street"
     },
     others: [
       {
         addressLine: "Mango Street"
       }
     ]
   }
}

现在这是令人困惑的部分。所以我没有在输入中包含locations。但保存在我的数据库中的数据如下所示:

{
  name: "john Doe",
  addresses: {
    primary: {
      addressLine: "Apple Street"
    },
    others: [
      {
         addressLine: "Mango Street",
         locations: {       <-- this locations suddenly shown!
           coordinates: []
         }
      }
    ]
  }
  _id: randomString,
  __v: 0
}

请帮忙,提前谢谢你:D

【问题讨论】:

    标签: javascript mongodb typescript mongoose


    【解决方案1】:

    在这种情况下,locations 会自动添加到您的子文档中,因为其中有 coordinates 字段。

    每当您在架构中定义数组 enter code heretype 字段时,如果未提供值,Mongoose 会自动将其初始化为空数组。

    而且,由于您没有将任何值传递给locations.coordinates,它会将其初始化为一个空数组。

    如果你想测试这个理论,请将coordinates从locations中删除,你会看到不同的。

    【讨论】:

    • 但locations 未显示在primary 属性中。仅显示在others
    猜你喜欢
    • 2023-03-04
    • 2019-08-01
    • 2016-07-15
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2013-10-05
    • 2015-06-26
    相关资源
    最近更新 更多