在Mongoose中填充+聚合

Gui*_*rme 12 mongoose mongodb node.js

我有两个Mongoose模型:一个用于事务,另一个用于与之关联的标记.为了实现一些报告,我需要像这样的聚合代码:

Transaction.aggregate([
  { $unwind: '$tags' },
  {
    $group: {
      _id: '$tags',
      amount: {
        $sum: '$amount'
      }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

这会产生包含_id和的输出amount.现在,我想name从模型中填充其他字段(例如),保留计算amount列.我能在一个简单的内容中做到populate吗?

编辑

我描述的模型的模式:

var TransactionSchema = new Schema({
  description: {
    type: String,
    trim: true
  },
  amount: {
    type: Number,
    required: 'Forneça um valor',
  },
  date: {
    type: Date,
    required: 'Forneça uma data',
    default: Date.now
  },
  fromOfx: {
    type: Boolean,
    default: false
  },
  created: {
    type: Date,
    default: Date.now
  },
  correlated: {
    type: Boolean,
    default: false
  },
  tags: [{
    type: Schema.Types.ObjectId,
    ref: 'TransactionTag'
  }],
  correlates: [{
    type: Schema.Types.ObjectId,
    ref: 'Transaction'
  }],
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

var TransactionTagSchema = new Schema({
  name: {
    type: String,
    required: 'Forneça um nome',
    trim: true
  },
  description: {
    type: String,
    trim: true
  },
  amount: {
    type: Number
  }
});
Run Code Online (Sandbox Code Playgroud)

Tho*_*ans 28

从MongoDB获取数据后,可以填充聚合.这看起来像这样:

// Your aggregate query from your question
Transaction.aggregate([{
                            $unwind: '$tags'
                        }, {
                            $group: {
                                _id: '$tags',
                                amount: {
                                    $sum: '$amount'
                                }
                            }
                        }])
    .exec(function(err, transactions) {
        // Don't forget your error handling
        // The callback with your transactions
        // Assuming you are having a Tag model
        Tag.populate(transactions, {path: '_id'}, function(err, populatedTransactions) {
            // Your populated translactions are inside populatedTransactions
        });
    });
Run Code Online (Sandbox Code Playgroud)

  • 完美的!我试图用 `{path: 'tags'}` 传递 populate,现在我想想,这让我觉得有点傻。现在再做一件事,这样做会将我的标签扔到 `_id` 字段中。有没有一种 Mongo-y 方法可以让它们转到 `tags` 属性? (2认同)