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?
问问题
719 次
1 回答
0
你可以做什么 :
解决方案之一是拥有一个有 id 的家庭模型,并且在用户模型中我会有一个带有家庭 id 的字段(如果您认为不需要家庭模型,您可以只拥有一个带有姓氏的字段,但是它每个家庭都必须是独一无二的)。
以家庭模型为例:
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' }
});
以姓氏作为字符串的简单示例:
var PersonSchema = new Schema({
name : String,
family : String
});
另外,如果您在用户模型中的家庭字段上放置一个索引,那么检索某人的所有家庭成员会非常快。以下是有关 mongodb 数据库中索引的更多信息:http: //docs.mongodb.org/manual/indexes/
解决方案二您可以使用包含所有家庭成员的集合、家庭模型。
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' }]
});
于 2015-01-08T20:02:46.807 回答