I'm curious what the best solution is for how to model this scenario where I have multiple types of entities that can be referenced by a single property. I see in THIS POST the way to make a foreign key is to have a property of type ObjectId and a reference to the applicable model. So in my scenario, should I have a single property of type String with an index on it and omit the reference?
Here's an abstract example of what I mean.. Say I have 3 types of animals: Dogs, Cats, and Pigs.. Then say any one of those animals can go visit the Vet. So I have a VetVisit schema that has a petId that can reference the _id of a Dog, Cat or Pig. My question is.. how should i model the petId? am I doing it right? See code examples below...
Dog:
var mongoose = require('mongoose');
var dogSchema = new mongoose.Schema({
name: {type: String},
age: {type: Number}
});
var Dog = mongoose.model('Dog', dogSchema);
module.exports = Dog
Cat:
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
Pig:
var mongoose = require('mongoose');
var pigSchema = new mongoose.Schema({
name: {type: String},
isMuddy: {type:Boolean}
});
var Pig = mongoose.model('Pig', pigSchema);
module.exports = Pig
Vet Visit:
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