首页 > 解决方案 > 在 MongoDb 中,是子文档引用还是扩展

问题描述

使用猫鼬,您可以创建一个子文档,如下所示:

export const UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: "email is required.",
        match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
    },
    firstName: {
        type: String,
        required: "firstName is required."
    },
    lastName: {
        type: String,
        required: "lastName is required."
    },
    dateOfBirth: {
        type: Date,
        required: "dateOfBirth is required."
    },
    roles: [{
        role: String,
        required: "role is required",
        validate: isValidUserRole
    }],
    address: AddressSchema,
});

地址架构

export const AddressSchema = new Schema({
    streetAddress: {
        type: String
    },
    addressLine2: {
        type: String
    },
    city: {
        type: String
    },
    state: {
        type: String
    },
    zipCode: {
        type: String
    },
    country: {
        type: String
    }
});

每当我保存用户时,猫鼬会创建一个包含嵌套地址数据或用户和地址的新用户文档,然后在用户实例中引用该地址文档吗?

我将如何处理 2 个用户共享相同地址的情况?

谢谢!

标签: mongodb

解决方案


你可以通过mongoshell 查询你的数据来发现这一点。

当文档包含嵌入文档(这与 shell 中的嵌套哈希无法区分)时,嵌入文档完全属于顶级文档,不能通过引用包含到另一个文档中。


推荐阅读