我有用户和用户都有文件。用户最多可以有100个文档。用户最多只能编辑50个文档。当我插入一个新文档时,首先我查询User.documents以查找文档数,然后我使用userId
和isFinished=true
查询文档,并检查是否有可编辑文档的空间。有没有办法通过单个查询获取用户的total
和finished
文档?我目前的代码如下所示。
var UserSchema = mongoose.Schema({
email: {type: String, index: {unique: true, sparse: true}},
password: String,
});
UserSchema.virtual('documents',{
ref: 'Document',
localField:'_id',
foreignField:'owner'
});
var DocumentSchema = mongoose.Schema({
owner : { type:mongoose.Schema.Types.ObjectId, ref: 'User' },
name: String,
data: String,
isFinished: {
type: Boolean, default: false
},
updateDate: Date
});
User.findOne({_id: req.userId}).populate('documents').exec(function(err, user) {
// user.documents == total user documents
if (user.documents && user.documents.length < 100) {
Document.count({owner:req.userId,isFinished:true},function(err,count) {
// count == finished user documents
if (count < 50) {
// do something
}
})
}
})
答案 0 :(得分:0)
我想我已经用聚合解决了这个问题。
Document.aggregate([
{
$match: {
owner:user._id
}},
{ $group: {
"_id": "$owner",
"totalCount": {
$sum: 1
},
"finishedCount" : { $sum: { $cond: ["$isFinished",1,0]} }
}
}]).exec(function (err,result) {
if ( result && result.length > 0) {
if ( result[0].totalCount >= config.registeredTotalLimit) {
// Registered total limit is reached
console.log('Register registeredTotalLimit');
}
if (result[0].finishedCount >= config.registeredActiveLimit) {
// Registered active limit is reached
console.log('Register registeredActiveLimit');
}
}