【问题标题】:mongoose how to perform aggregation on ref fields猫鼬如何对 ref 字段执行聚合
【发布时间】:2014-01-12 13:57:28
【问题描述】:

如何在 mongoose 中对基于其他模式的 ref 的字段执行聚合..

例如:下面的 id 架构

var StorySchema = new Schema({
    _creator : { type: Schema.ObjectId, ref: 'Person' }
  , title    : String
  , fans     : [{ type: Schema.ObjectId, ref: 'Person' }]
});

如何与创作者和粉丝进行聚合

提前感谢

【问题讨论】:

  • 如果您指的是聚合框架,它仅限于一个集合(由 MongoDb 提供)。

标签: node.js mongodb reference mongoose aggregation-framework


【解决方案1】:

可以使用populate函数,文档:http://mongoosejs.com/docs/populate.html

populate 将帮助您根据 ObjectId 和 ref 集合查找数据库:

Story
  .findOne({title: 'your title'})
  .populate(['_creator', 'fans'])
  .exec(function (err, doc) {
    console.log(doc);
})

输出:

{ _id: 52b9768a8a770b383d000003,
  title: 'your title',
  _creator: { name: 'user1', _id: 52b975e13e7f2dec31000001, __v: 0 },
  fans:
   [ { name: 'fan1', _id: 52b975e13e7f2dec31000001, __v: 0 },
     { name: 'fan2', _id: 52b975e13e7f2dec31000002, __v: 0 },
     { name: 'fan3', _id: 52b975e13e7f2dec31000003, __v: 0 }] }

您可以删除填充功能以查看不同的结果

【讨论】:

  • 问题是关于聚合的?
  • @WiredPrairie 是的,我在上面看到了你的评论,我正在再次阅读这个问题,谢谢 :)
猜你喜欢
  • 2016-03-23
  • 2022-12-05
  • 2019-09-06
  • 1970-01-01
  • 2022-01-26
  • 2020-03-13
  • 2018-01-30
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多