最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

外键由多个模型组成

IT培训 admin 8浏览 0评论

外键由多个模型组成

我正在使用mongo和mongoose,我正在尝试为我的应用程序建模。 我有以下型号:ProductA,ProductB和ProductChat。 每个产品可以有很多聊天。每次聊天都与唯一的产品(A或B)相关。 我希望ProductChat能够引用相关的产品文档。我考虑过将productType,productId字段添加到ProductChat: const ProductChatSchema = new Schema({ ... ... productType: { type: 'String', required: true, enum: [ 'A', 'B' ] }, product: { type: Schema.Types.ObjectId, required: true, ref: '???' // Ref to what? }, ... ... }); 但是我不知道在'ref'上放什么...... 我想避免在ProductChat上添加productAId,productBId字段,因为可能有很多产品。 知道怎么做才对吗?

回答如下:

由于有许多产品,请将ProductChat ref提供给数组中的ProductsA(B,C ..)集合。

const productA = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

const productB = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

外键由多个模型组成

我正在使用mongo和mongoose,我正在尝试为我的应用程序建模。 我有以下型号:ProductA,ProductB和ProductChat。 每个产品可以有很多聊天。每次聊天都与唯一的产品(A或B)相关。 我希望ProductChat能够引用相关的产品文档。我考虑过将productType,productId字段添加到ProductChat: const ProductChatSchema = new Schema({ ... ... productType: { type: 'String', required: true, enum: [ 'A', 'B' ] }, product: { type: Schema.Types.ObjectId, required: true, ref: '???' // Ref to what? }, ... ... }); 但是我不知道在'ref'上放什么...... 我想避免在ProductChat上添加productAId,productBId字段,因为可能有很多产品。 知道怎么做才对吗?

回答如下:

由于有许多产品,请将ProductChat ref提供给数组中的ProductsA(B,C ..)集合。

const productA = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

const productB = new Schema({
    ProductChatIds: [{
        type: Schema.Types.ObjectId,
        ref: 'ProductChat'
    }]
});

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论