2017-03-19 16 views
1

我很好奇什么是最好的解决方案是如何建模这种情况下,我有多种类型的实体可以由单个属性引用。我在THIS POST中看到,创建外键的方式是拥有ObjectId类型的属性和对适用模型的引用。所以在我的情况下,我是否应该有一个String类型的单个属性,并在其中包含索引并省略引用?Mongoose模型设计ObjectId有条件地引用集合

下面是我的意思的抽象例子。说我有3种动物:狗,猫和猪。然后说这些动物中的任何一个都可以去拜访兽医。所以我有一个VetVisit架构,它有一个可以引用Dog,Cat或Pig的_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 

回答

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 
+0

哦完全..我给那些只是一个例子。在现实中,这些集合是非常不同的..不同,我不希望他们在同一个集合中。否则我会同意你在这里..你可以用我的例子做一个子类型超类型,它会工作。现在我想到了,也许我可以做一个子类型超级类型。感谢您的反馈 – Donuts

相关问题