【问题标题】:MongoError when trying to aggregate with collection relationship尝试与集合关系聚合时出现 MongoError
【发布时间】:2016-06-15 23:58:54
【问题描述】:

我是 mongodb 的新手,使用 meanjs.org 的平均堆栈。

我有一个具有用户集合关系的模型:

var MealSchema = new Schema({
  mealDate: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});
mongoose.model('Meal', MealSchema);

我找到了一个可行的实现:

var user = req.user;
Meal.find({
  mealDate: {
    $gte: minus8days.toDate(),
    $lt: tomorrow.toDate()
  },
  user : user
  }).exec(function (err, meals) {
  if (err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  } else {
    res.json(meals);
  }
});

但是我需要一些分组和聚合,所以我试图更改此代码以使用聚合而不是查找,我尝试了很多组合并且我不断收到错误,基本上以下实现会引发错误 MongoError: Maximum call超出堆栈大小

Meal.aggregate([
{
  $match: {
    $and: [
      {
        mealDate: {
          $gte: minus8days.toDate(),
          $lt: tomorrow.toDate()
        }
      }, { user: user }
    ]
  }
}]...

为什么 user:user 使用 find 而不是聚合? 如何修复聚合方法?

【问题讨论】:

  • 请尝试{ $match: { mealDate: { $gte: minus8days.toDate(), $lt: tomorrow.toDate() }, user: user } } 并在aggregation 末尾添加function(err),它可以为您提供更多有关错误的信息?
  • user的值是否正确ObjectId
  • 您给出的建议基本上是删除 $and 和数组括号不起作用,它给出了相同的错误(超出了最大调用堆栈)。用户的价值是正确的,正如我所提到的,它在 find 中的使用与此完全一样,并且可以正常工作。建议的函数错误已经存在,我只是省略了,因为它对问题没有太大影响。感谢您的帮助。

标签: mongodb mongoose mean-stack mean meanjs


【解决方案1】:

试试这个:

Meal.aggregate([
    { 
       $match: { 
           mealDate: { $gte: minus8days.toDate(), $lt: tomorrow.toDate()},
           user: user._id
       }
    }
], function(err, docs){
    if(err) console.log("Error : " + JSON.stringify(err));
    if(docs) console.log("Got the docs successfully : " + JSON.stringify(docs));
});

【讨论】:

  • 嗨,这可行,但我现在很困惑。 user:user 用于查找但不适用于聚合的原因是什么?有任何想法吗?谢谢
猜你喜欢
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
相关资源
最近更新 更多