从一个模式计算一个值,并将该值放在另一个模式mongodb节点中

var ProductSchema = new Schema({ title: {type: String}, rating : {type: Number}, ingredients : { type: String} }); var IngredientSchema = new Schema({ title: {type: String}, weightage : {type: String} }); 

例如:在ProductSchema中,配料字段是:“水,锌,尿素,硅土,钠”

每种成分由IngredientSchema定义

例:

 title : Water | Zincum | Urea | Silica | Sodium weightage: 5 | 7 | 3 | 2 | 9 

现在我有一个计算产品评分的公式:[所有成分的重量之和] / [产品成分的数量]

在我们的例子中:rating =(5 + 7 + 3 + 2 + 9)/ 5 = 5.2

现在在添加产品的api中,我想根据产品配料领域计算评分,然后存储在数据库中。

这个怎么做?

您需要参考IngredientProduct模式。 使用mongoose填充。

 var ProductSchema = new Schema({ title: {type: String}, rating : {type: Number}, ingredients : { Schema.ObjectId, ref: 'Ingredient'} }); var IngredientSchema = new Schema({ title: {type: String}, weightage : {type: String} }); 

进一步阅读: 在这里