将嵌套对象保存在mongoose中

我刚接触node.js和MongoDb(以及一般的文档数据库)。 从PHP / MySQL背景来看,我在构build和保存数据方面苦苦挣扎。

我试图创build一个小应用程序,我可以添加多种配料的食谱。 我有一堆预填充的成分作为种子数据,其模式如下所示:

var IngredientSchema = new Schema({ name: { type: String, trim: true, required: true, index: { unique: true } }, created: { type: Date, default: Date.now } }); var Ingredient = mongoose.model('Ingredient', IngredientSchema); 

配方目前看起来像这样:

 var RecipeSchema = new Schema({ name: { type: String, trim: true }, ingredients: [ { type: Schema.Types.ObjectId, ref: 'RecipeIngredient' } ], created: { type: Date, default: Date.now } }); var Recipe = mongoose.model('Recipe', RecipeSchema); 

最后,我有一个RecipeIngredientSchema。 现在,这是我的MySQL背景可能正在蔓延的地方。 我这样做的原因是因为我想要食谱和配料之间的一对多的关系,但我也希望能够指定一个单位:

 var RecipeIngredientSchema = new Schema({ recipe: { type: Schema.Types.ObjectId, ref: 'Recipe' }, ingredient: { type: Schema.Types.ObjectId, ref: 'Ingredient' }, unit: { type: Schema.Types.ObjectId, ref: 'Unit' }, created: { type: Date, default: Date.now } }); var RecipeIngredient = mongoose.model('RecipeIngredient', RecipeIngredientSchema); 

我的问题分两部分:

  • 我是从数据build模的angular度以合理的方式来讨论这个问题,还是我离开了?
  • 保存多种配料食谱的过程实际上是什么样子?

我目前正在考虑以下几点:

 exports.create = function(req, res) { var recipe = new Recipe(req.body); recipe.save(function(err, recipe) { if (err) { return res.jsonp(err); } else { // Loop ingredients if (req.body.ingredients) { for(var prop in req.body.ingredients) { var recipeIngredient = new RecipeIngredient({ recipeId: recipe._id, ingredientId: mongoose.Types.ObjectId(req.body.ingredients[prop]) }); recipeIngredient.save(function(err, recipeIngredient) { if (err) { return res.jsonp(err); } else { recipe.recipeIngredients.push(recipeIngredient._id); recipe.save(function(err, recipe) { return res.jsonp(recipe); }); } }); }; } } }); } 

我觉得这是错综复杂的,一般错误的 ,所以将不胜感激一些指导!

NoSQL数据库(或者一般的文档存储)的优点在于,您不必将数据拆分为多个表/集合。 您可以将所有相关数据存储到一个实体中,以便您的读取操作一次性完成。

没有“正确”的方法来做到这一点,但如果你要使用NoSQL,我会考虑将整个配方(配方和成分和方向)作为一个单独的文件保存,而不是将数据分成3或4个表格a-la关系模型。

例如,我会保存一个配方,如下所示:

 recipe = { name: 'name of recipe' time: '45 minutes' ingredients : [ {qty: 3, unit: 'item', name: 'tomatoes'}, {qty: 0.5, unit: 'tbs', name: 'salt'}, {qty: 1, name: 'item', name: 'avocado'} ] } 

现在,这不是精灵之尘。 有时候将数据拆分成多个表/集合,并且有一个关系查询语言(如SQL)将有利于查询数据。 例如,如果您想要查询所有使用“西红柿”的配方关系数据库配方关系的配方关系的配方会比NoSQL方法更简单。

这是你需要做出的一个决定:对于你的应用程序你更喜欢NoSQL还是RBMS?

如果你想在数据库中保存嵌套的对象,你有两个select:embedded式模式或参考。 如果用引用将它们保存,则嵌套模式将保存在单独的集合中。

开始看看这个例子mongo-many-to-many和这一节:saving-refs