【问题标题】:Mongoose populate count猫鼬种群数量
【发布时间】: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


    【解决方案1】:

    Mongoose 将在幕后对所有与找到的任何办公室 ID 匹配的用户进行查询,正如您可能知道的那样,这就是您获得相同计数的原因。

    但是由于 Mongoose 将其作为单独的查询执行,因此没有什么可以阻止您自己在后挂钩中执行相同的操作。见https://mongoosejs.com/docs/middleware.html#post-async

    因此,在返回所有办公室后,您需要获取所有用户,按他们的办公室对他们执行一个组(参见 group),并计算每个结果组中的数量(参见 count)。

    此时,您可能需要考虑执行与聚合管道相同的操作,这可以在服务器端更有效地执行。 请参阅为聚合模型方法编写组管道: https://docs.mongodb.com/manual/reference/operator/aggregation/group/

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 2017-06-02
      • 1970-01-01
      • 2018-02-10
      • 2013-11-27
      • 2016-12-17
      • 2018-09-13
      • 2016-07-02
      • 2016-07-11
      相关资源
      最近更新 更多