Javascript 如何在mongoose模式中表示范围? 背景
假设我正在做一个关于你可以买到的水果的模式。在此模式中,水果的价格范围为:Javascript 如何在mongoose模式中表示范围? 背景,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,假设我正在做一个关于你可以买到的水果的模式。在此模式中,水果的价格范围为: let fruit = { name: "banana", price: { currency: "EUR", range: [2, 10] } }; 为了保存上述对象,我尝试使用以下模式: let fruitSchema = { name: {type: String, required: true}, price: { curr
let fruit = {
name: "banana",
price: {
currency: "EUR",
range: [2, 10]
}
};
为了保存上述对象,我尝试使用以下模式:
let fruitSchema = {
name: {type: String, required: true},
price: {
currency: {type: String, required: true},
range: [{
type: Number,
min: 0
}],
validate: [arraySize]
}
};
const arraySize = function arrayLimit(val) {
return val.length === 2;
};
问题:
我对范围部分的解决方案感觉笨重、过于复杂,并且没有检查最大范围值是否大于最小范围值,即,没有检查10>2
问题:
- 您将如何在mongoose的模式中实现价格范围
income: {
currency: { type: String },
range: {
min: { type: Number, min: 0 },
max: { type: Number, min: 0 }
}
}
问题
然而,现在我有一个问题。如何始终检查my
MAX>=MIN
,以及MIN为什么不将模式设计更改为范围:{minimum:{type:Number,MIN:0},maximum:{type:Number,MIN:0}
,这将使查询更容易。我觉得这也有道理。但是,如何检查最大值>最小值?
validate: {
validator: function(val){
const currMax = this.target.income.range.max;
return (currMax !== undefined ? val <= currMax : true);
},
message: "The MIN range with value {VALUE} must be <= than the max range!"
}
validate: {
validator: function(val) {
const currMin = this.target.income.range.min;
return (currMin !== undefined ? val >= currMin : true);
},
message: "The MAX range with value {VALUE} must be >= than the min range!"
}
income: {
currency: { type: String },
range: {
min: {
type: Number, min: 0,
validate: {
validator: function(val){
const currMax = this.target.income.range.max;
return (currMax !== undefined ? val <= currMax : true);
},
message: "The MIN range with value {VALUE} must be <= than the max range!"
}
},
max: {
type: Number, min: 0,
validate: {
validator: function(val) {
const currMin = this.target.income.range.min;
return (currMin !== undefined ? val >= currMin : true);
},
message: "The MAX range with value {VALUE} must be >= than the min range!"
}
}
}
}
Model.findOne({ name: 'borne' }, function (err, doc){
doc.name = 'jason borne';
doc.visits.$inc();
doc.save();
});