1

I am using nodejs and mongoose and I want to save a family tree to mongoose. My question is for the schema. What will be better: to have a person schema in which there is an array field which stores the ids of the family members or there is some other way to do so. Because if I want to get a person with all his family members the machine must go through all the people and check them if they are family members of the person. Is there more efficient way?

1 Answers1

0

What you can do :

Solution one is to have family model which have a id and in the user model I would have a field with the family id (if you don't think a family model is needed you can just have a field with a family name, but it will need to be unique for each family).

Exemple with family model:

var FamilySchema = new Schema({
  name: String
});

var family = db.model('family', FamilySchema);

var PersonSchema = new Schema({
 name : String,
 family : { type : Mongoose.Schema.ObjectId, ref : 'family' }
});

Simple exemple with family name as a string:

var PersonSchema = new Schema({
 name : String,
 family : String
});

Plus if you put a index on the family field in the user model it would be really fast to retrieve all the family members of someone. Here is more about index in mongodb database : http://docs.mongodb.org/manual/indexes/

Solution two you can make use of a collection, family model containing all the family members.

var PersonSchema = new Schema({
  name : String
});

var person = db.model('person', PersonSchema);

var FamilySchema = new Schema({
  name : String,

  members : [{ type : Mongoose.Schema.ObjectId, ref : 'person' }]
});

Alois
  • 36
  • 4