【发布时间】:2014-02-10 04:24:28
【问题描述】:
来自 PHP/MySQL 背景,我在构建和保存数据方面的最佳实践中苦苦挣扎。
我正在尝试创建一个小型应用程序,我可以在其中添加具有多种成分的食谱。我有一堆预先填充的成分作为种子数据,其架构如下所示:
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);
我的问题分为两部分:
- 我是在数据建模方面以一种明智的方式解决这个问题,还是离题?
- 保存具有多种成分的配方的过程实际上是什么样的?
我目前正在考虑以下几点:
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);
});
}
});
};
}
}
});
}
我觉得这很复杂,而且通常错,所以希望得到一些指导!
【问题讨论】:
标签: node.js mongodb express mongoose