如何在猫鼬中创建这个架构?

时间:2021-03-07 22:00:01

标签: mongoose

一直在谷歌搜索,但不确定我会怎么称呼它,所以没有找到任何关于它的教程。

如果我有一个看起来像这样的 json

{
    "firstName": "jim",
    "lastName": "smith",
    "identifications": [{
        "passport": {
            "expiry": "2020-01-01",
            "nicknames": ["Jim", "J"]
        },
        "driverLicense": {
            "expiry": "2020-01-01",
            "restrictions": ["glasses"]
        }
    }]
    
}

我有这个,但我不知道如何处理身份验证。我需要为它制作一个新的模式吗?或者怎么写。我也不确定是否需要对每个属性中的每个属性进行规范化(即护照有昵称但 driverLicense 没有,我是否都需要它?)

const CreditCardSchema = mongoose.Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    identifications: ??
    
});

1 个答案:

答案 0 :(得分:2)

这应该是您要找的。

Mongoose 模式可以根据需要反复嵌套。

显然,您可以使用此架构获得更具体的信息,例如验证到期日期。

const CreditCardSchema = mongoose.Schema({
  firstName: {type: String, required: true},
  lastName: {type: String, required: true},
  identifications: [
    {
      expiry: {
        type: String,
        required: true,
      },
      nicknames: [String],
      restrictions: [String],
    }
  ],
});

因为标识可以有不同的字段(如昵称和限制),这些字段可能不会出现在所有标识上,所以最好为这些标识定义更多模式。

考虑制作另一个名为 Identification 的模型,然后您可以像这样使用它:

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const CreditCardSchema = mongoose.Schema({
  firstName: {type: String, required: true},
  lastName: {type: String, required: true},
  identifications: [
    {
      type: ObjectId,
      ref: 'Identification',
    },
  ]
});

一旦你成功了,你就可以做let Passport = new Identification({ ... }),然后运行CreditCard.identifications.push(Passport),然后砰的一声,他们就连在一起了!

相关问题