node.js - Mongoose 数量

标签 node.js mongoose count schema populate

我想知道有多少用户与我的办公室关联,为此我使用虚拟架构的计数选项。

办公室架构:

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 } });

Office-用户关系:

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' }
  ]);

但是,当没有查询对象时(意味着获取所有办公室及其用户数),我会得到每个办公室的相同用户数,即总数。 我只想获取每个办公室的相关用户数量。这可能吗?

最佳答案

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

但是因为 Mongoose 是作为一个单独的查询来执行此操作的,所以没有什么可以阻止您在后 Hook 中自己执行相同的操作。请参阅https://mongoosejs.com/docs/middleware.html#post-async

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

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

关于node.js - Mongoose 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55831663/

相关文章:

node.js - 错误 : ENOENT with Bunyan rotating-file logging (NodeJS)

node.js - node-forge 如何从文件中读取私有(private) rsa key

node.js - NodeJS 0.10.46 在lighttpd代理之后不再提供服务

php - 作为查询的一部分计数

arrays - 计数查询、物化 View 的 PostgreSQL 效率

javascript - Node.js + Express 路线未按预期工作

javascript - 如何过滤 Backbone.js Collection 和 Rerender App View?

node.js - 使用 Typescript 在 Mongoose 中链接 ES6 Promise

node.js - Mongoose 递归填充

r - 计算字符串中出现在 R 字符串中特定位置的单词