【发布时间】:2019-09-13 20:18:09
【问题描述】:
我想知道有多少用户与我的办公室相关联,为此我使用虚拟模式的计数选项。
办公室架构:
const OfficeSchema = mongoose.Schema({
name: { type: String },
admin: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
}, { toJSON: { virtuals: true } });
用户架构:
const UserSchema = mongoose.Schema({
email: { type: String, unique: true, required: true },
first_name: { type: String },
last_name: { type: String },
office: { type: mongoose.Schema.Types.ObjectId, ref: 'Office' },
}, { toJSON: { virtuals: true } });
办公室-用户关系:
OfficeSchema.virtual('usersCount', {
ref: 'User',
localField: '_id',
foreignField: 'office',
justOne: false,
count: true
});
当我向 find 方法添加查询参数时,它工作正常,我得到了特定办公室的用户数。
Office.find({ admin: userId }).populate([
{ path: 'admin', select: '_id email first_name last_name' },
{ path: 'usersCount', select: '_id' }
]);
但是当没有查询对象时(意味着获取所有办公室及其用户数),我会为每个办公室获得相同数量的用户,即总数。 我只想获取每个办公室的相关用户数。这可能吗?
【问题讨论】:
标签: node.js mongoose count schema populate