我对NoSQL和mongodb完全陌生,并且基于在线课程,我能够设置一个简单的数据库,该数据库包含三个集合:
1)用户集合-包含应用程序的用户
2)水箱收集-每个用户可以拥有的水箱
3)使用情况收集-包含每次访问储罐的记录。
我将其设置如下:
//用户架构
const UserSchema = new mongoose.Schema({
username: {
type: String,
unique : true,
required: true,
trim: true,
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
name: {
// TODO : Add validation for name
type: String,
required: true
},
mobile:{
// TODO : Add validation for mobile numbers
type: String
},
waterAllocated:{
type: Number,
default : 50
},
tokens: [{
token: {
type: String,
required: true
}
}]
}, {
timestamps: true
});
UserSchema.virtual('tanks', {
ref: 'Tank',
localField: '_id',
foreignField: 'owner'
})
//储罐模式
const TankSchema = new mongoose.Schema({
label : {
type: String,
unique: true,
required: true
},
maxCapacity: {
type: Number,
required : true
},
motorRunning: {
type: Boolean,
default: false
},
curLevel:{
type: Number,
default: 0,
min : [0, "Tank empty"],
validate(value) {
if(value > this.maxCapacity) {
throw new Error("Current level cannot exceed max capacity")
}
}
},
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
})
TankSchema.virtual('usages', {
ref: 'Usage',
localField: 'label',
foreignField: 'tank'
})
TankSchema.pre('remove', async function (next) {
const tank = this
await Usage.deleteMany({ tank: tank.label })
next()
})
//使用模式
const UsageSchema = mongoose.Schema({
waterUsed:{
type: Number,
required : true
},
flow:Number,
tank: {
type: String,
required: true,
ref: 'Tank'
}
}, {
timestamps: true
});
所以就像 用户->坦克->使用情况
现在,我想执行诸如在特定用户的所有容器和用法中获取waterUsed
之和的操作,但是我不知道如何开始进行聚合,而且我很难理解这个。
如何计算集合中的总和?