【问题标题】:How to inherit a mongoose model and store it in a different collection如何继承猫鼬模型并将其存储在不同的集合中
【发布时间】:2016-05-01 00:55:27
【问题描述】:

我需要创建一个与现有模型(原始)几乎相同的模型(新)。新模型将有一个新字段(“expiresAt”),我想将其用于 MongoDB 生存时间 (TTL) 功能。 出于设计目的,我不想将 NEW 模型与 ORIGINAL 存储在同一个集合中(只有 NEW 模型应该具有 TTL 功能)。

例子:

//ORIGINAL schema

var OriginalSchema = new Schema({

    id: { type: Schema.Types.ObjectId },
    name: { type: String },
    description: { type:String },
});


//NEW schema

var NewSchema = new Schema({

    id: { type: Schema.Types.ObjectId },
    name: { type: String },
    description: { type:String },
    expiresAt: { 
        type: Date, 
        default: Date.now,
        expires: 24*60*60
    }
});

如何通过继承来实现?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Mongoose discriminators 是一种模式继承机制。它们使您能够在同一个基础 MongoDB 集合之上拥有多个具有重叠模式的模型。这个link谈了一些细节。

    var OriginalSchema = new Schema({
        id: { type: Schema.Types.ObjectId },
        name: { type: String },
        description: { type:String },
    });
    
    var NewSchema = new Schema({
        expiresAt: { 
            type: Date, 
            default: Date.now,
            expires: 24*60*60
        }
    });
    
    var Original = mongoose.model('Original', OriginalSchema);
    var NewSch = Original.discriminator('NewSch', NewSchema);
    

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 2013-09-15
      • 2016-01-27
      • 2012-12-23
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多