1
votes

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
1

1 Answers

1
votes

Your Vet Visit: schema seems correct to me but you can combine your dog, cat, pig collections in one collection because if you have 10 animals you have multiple animals there is no need to make multiple collections you can just define the size of animal and you can perform any query on the bases of type of animal.

    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