MongoDB模型字段是乘以2个字段的结果

我有一个小问题试图找出哪个是最好的方法来做到这一点:

我有一个表格,可以通过两个单选button以两种不同的方式为用户业务设置定价:

成员,我有两个领域,“每个成员的数量”和“数量”。 数量上,我只有一个字段,“总金额”。

而且我必须将这些数据存储在数据库中名为“价格”的字段中。 所以,如果我提交“按成员”选项的表格,“价格”将是“每个成员的金额”*“数量”的结果。 如果我用“按金额”选项提交表格,“价格”应该是“总金额”字段值。

这里的事情是,我不知道在模型上哪个是最好的方式来pipe理这个“有条件的”东西,所以也许你可以帮助我:D。

谢谢!

如果你正在为你的模型使用mongoose ,你可以做这样的事情:

var mongoose = require('mongoose'); var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/nodetest') // Define schema var formSchema = new Schema({ member: { type: Boolean, default: false }, qty: { type: Number, default: 0 }, amount: { type: Number, default: 0 }, price: { type: Number, default: 0 } }); // Set up some getters and setters to calculate formSchema.path('price').get(function(value) { if (!this.member) { return this.qty * this.amount; } return value; }); formSchema.path('qty').set(function(value) { if (!this.member) { this.price = value * this.amount; } return value; }); formSchema.path('amount').set(function(value) { if (!this.member) { this.price = this.qty * value; ) return value; }); // Define the model for the Schema var Form = mongoose.model('Form', formSchema); // Then use in your code var form1 = new Form({ qty: 2, amount: 10 }); var form2 = new Form({ qty: 3, amount: 10, member: true, price: 25 }); console.log( form1 ); console.log( form2 ); 

因此,这将填写在您的模型中的price字段与计算值的member值如果为false,但在哪里是true那么你传入的值将永远被兑现。

我将把表格处理留给你,但是这就是你如何在你的模型中坚持你的逻辑。