Mongoose 如何使用猫鼬吸气剂
我的mongoose模式中有三个字段,我只想检索其中一个字段,它将是其他两个字段的平均值 我试图使用猫鼬获取,但我不知道我是否正确使用了它 这是我的模式Mongoose 如何使用猫鼬吸气剂,mongoose,Mongoose,我的mongoose模式中有三个字段,我只想检索其中一个字段,它将是其他两个字段的平均值 我试图使用猫鼬获取,但我不知道我是否正确使用了它 这是我的模式 const schema = new Schema({ totalCarrots: {type: Number}, numberOfRabbits: {type: Number}, average: { type: Number, get: function () {
const schema = new Schema({
totalCarrots: {type: Number},
numberOfRabbits: {type: Number},
average: {
type: Number,
get: function () {
const average = this.totalCarrots / this.numberOfRabbits;
if (average) return Math.ceil(average);
return null;
}
}
});
我希望average返回计算值。如何存档此文件?看起来您根本不需要
获取
。由于您只是希望生成一个动态值,因此可以在模式的方法上创建自己的方法,如下所示:
schema.methods.average = function(){
const average = this.totalCarrots / this.numberOfRabbits;
return average ? Math.ceil(average) : null;
}
现在,您可以在架构的实例上调用此方法:
const doc = new schema({ totalCarrots: 4, numberOfRabbits: 2 })
doc.average() // should return 2
get
用于实际存储数据的字段,当您访问该字段时,它可以修改该字段。例如,假设我们有一个带有price
字段的产品模型。我们的价格是以浮动形式存储的,无论出于什么原因,我们每次读取价格时都要对其进行四舍五入。这将是使用get
方法的好地方:
const ProductSchema = new Schema({
price: {
type: Number,
get: function(value){
// value arg is referring to the value of a model instance's price
return Math.round(value)
}
}
})
const Product = mongoose.model('Product', ProductSchema)
const product = new Product({ price: 15.80 })
product.price // will be 16 because we round the stored value in the get method
看起来实际上你根本不需要get
。由于您只是希望生成一个动态值,因此可以在模式的方法上创建自己的方法,如下所示:
schema.methods.average = function(){
const average = this.totalCarrots / this.numberOfRabbits;
return average ? Math.ceil(average) : null;
}
现在,您可以在架构的实例上调用此方法:
const doc = new schema({ totalCarrots: 4, numberOfRabbits: 2 })
doc.average() // should return 2
get
用于实际存储数据的字段,当您访问该字段时,它可以修改该字段。例如,假设我们有一个带有price
字段的产品模型。我们的价格是以浮动形式存储的,无论出于什么原因,我们每次读取价格时都要对其进行四舍五入。这将是使用get
方法的好地方:
const ProductSchema = new Schema({
price: {
type: Number,
get: function(value){
// value arg is referring to the value of a model instance's price
return Math.round(value)
}
}
})
const Product = mongoose.model('Product', ProductSchema)
const product = new Product({ price: 15.80 })
product.price // will be 16 because we round the stored value in the get method