【问题标题】:Mongoose model design for ObjectId conditionally referencing collectionObjectId 条件引用集合的 Mongoose 模型设计
【发布时间】:2017-08-11 01:12:35
【问题描述】:

我很好奇在我有多种类型的实体可以由单个属性引用的情况下,如何建模这种场景的最佳解决方案是什么。我在THIS POST 中看到创建外键的方法是拥有 ObjectId 类型的属性和对适用模型的引用。所以在我的场景中,我应该有一个字符串类型的属性,上面有一个索引并省略引用吗?

这是我的意思的一个抽象示例。假设我有 3 种动物:狗、猫和猪。然后说这些动物中的任何一种都可以去看兽医。所以我有一个 VetVisit 模式,它有一个可以引用狗、猫或猪的 _id 的 petId。我的问题是..我应该如何为 petId 建模?我做对了吗?请参阅下面的代码示例...

狗:

var mongoose = require('mongoose');

var dogSchema = new mongoose.Schema({
    name: {type: String},
    age: {type: Number}
});

var Dog = mongoose.model('Dog', dogSchema);
module.exports = Dog

猫:

var mongoose = require('mongoose');

var catSchema = new mongoose.Schema({
    name: {type: String},
    age: {type: Number},
    isLongHair: {type:Boolean}
});

var Cat = mongoose.model('Cat', dogSchema);
module.exports = Cat

猪:

var mongoose = require('mongoose');

var pigSchema = new mongoose.Schema({
    name: {type: String},
    isMuddy: {type:Boolean}
});

var Pig = mongoose.model('Pig', pigSchema);
module.exports = Pig

兽医访问:

var mongoose = require('mongoose');

var vetVisitSchema = new mongoose.Schema({
    petType: {
        type: String, // dog, cat, pig
        required: [true,"Pet type is required"]
    },
    petId: {
        type: String, 
        required: [true,"Pet ID is required"]
    },
    date: {
        type: Date,
        required: [true, "Date is required"]
    },
    Reason: {
        type: String,
        required: [true, "Reason is required"]
    }
});

module.exports = vetVisitSchema

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    您的兽医访问:架构对我来说似乎是正确的,但您可以结合您的狗、猫、猪 一个集合中的集合,因为如果您有 10 只动物,您就有多个动物,则无需创建多个集合,您只需定义动物的大小,您可以根据动物类型执行任何查询。

        var mongoose = require('mongoose');
    
        var Animal= new mongoose.Schema({
            name: {type: String},
            petType: {
            type: String, // dog, cat, pig
                required: [true,"Pet type is required"],},
           isLongHair: {type:Boolean}
             isMuddy: {type:Boolean},
                    age: {type: Number}
                });
    
            var Animal= mongoose.model('Animal', animalSchema);
            module.exports = Animal
    

    【讨论】:

    • 哦,完全......我只是举个例子。实际上,这些收藏品完全不同.. 差异很大,以至于我不希望它们在同一个收藏品中。否则我会同意你的看法。你可以用我的例子做一个子类型超类型,它会起作用。现在我想起来了,也许我可以做一个子类型超类型。感谢您的反馈
    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 2017-03-16
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2014-09-11
    • 2015-04-21
    相关资源
    最近更新 更多