mongodb - Reference field within same schema -
is possible reference field within same schema? see example below. or going wrong way?
var userschema = new mongoose.schema ({ username: string, password: string, email: string, foods: [{ name: string, category: string, ingredients: // how reference values in ingredients array? }], ingredients: [{ name: string, category: string }] });
short answer
this core mongodb design decision: mongodb relationships: embed or reference?
storing references objects, rather independent copies of them, in relational database possible in mongodb , done, results in more , more complex queries when need them up.
long answer
if goal keep definitions of ingredient schemas consistent, can define schema , use twice. ingredients stored independent copies, e.g.
[{ username: 'bob', ingredients: [ { name: 'carrot', category: 'vegetable' } , ...], foods: [ { name: 'salad', category: 'lunch', ingredients: [ { name: 'carrot', category: 'vegetable'}, ...]}] }, ...] var ingredientschema = new mongoose.schema({ name: string, category: string, }); var userschema = new mongoose.schema ({ username: string, password: string, email: string, foods: [{ name: string, category: string, ingredients: [ingredientschema] // brackets indicates it's array, }], ingredients: [ingredientschema] });
alternatively can reference ingredients objectid:
var userschema = new mongoose.schema ({ username: string, password: string, email: string, foods: [{ name: string, category: string, ingredients: [mongoose.schema.types.objectid] // ids reference individual ingredients, }], ingredients: [ingredientschema] });
by defining ingredientschema explicitly, each ingredient object gets own objectid when declared. upside storing ids of ingredients (rather copies of ingredient objects) more concise , consistent storage. downside there many more , more complex queries.
[{ username: 'bob', ingredients: [ { _id: objectid('a298d9ef898afc98ddf'), name: 'carrot', category: 'vegetable' } , ...], foods: [ { name: 'salad', category: 'lunch', ingredients: [ {$oid: 'a298d9ef898afc98ddf'}, ]}] }, ...]
a better approach if want store references ingredients, may store ingredients own first class collection. you'll still have many separate queries when want foods ingredient, or ingredients food, queries simpler.
var userschema = new mongoose.schema ({ username: string, password: string, email: string, foods: [{ name: string, category: string, ingredients: [mongoose.schema.types.objectid] // ids reference individual ingredients, }], ingredients: [mongoose.schema.types.objectid] });
if goal store normalized references ingredients , search foods based on them, quote [so post][1], "this 1 of cases relational databases shine"
see post querying subdocuments id: reading categories , number of articles in single query
as 1 respondent notes, "this 1 of cases relational databases shine"
Comments
Post a Comment