Mongoose聚合返回空结果并在mongo控制台中工作

时间:2016-03-26 20:22:47

标签: node.js mongodb mongoose

堆栈:  + Mongoose 4.4.10(最后稳定版)已经使用旧版本进行了测试  + MongoDb 2.6.3

我在mongodb控制台中执行该功能,成功重新

db.activities.aggregate(
    { $match : { 'organizer': ObjectId("5408e4609640de8768c1d212") } }
  , { $group : 
       { _id : "$organizer",  
        totalSwims: { $sum : 1 }, 
        longestSwim :  { $max: "$distance" }, 
        moreDistanceSwim :  { $max: "$duration" }, 
        warmestWaterSwim :  { $max: "$activityWeather.waterTemperature" }, 
        coldestWaterSwim :  { $min: "$activityWeather.waterTemperature" }, 
        warmestSwim :  { $max: "$activityWeather.temperature" }, 
        coldestSwim :  { $min: "$activityWeather.temperature" }}});

{“_ id”:ObjectId(“5408e4609640de8768c1d212”),“totalSwims”:50,“longestSwim”:6512.997,“moreDistanceSwim”:“02:35”,“warmestWaterSwim”:“22”,“coldestWaterSwim”:“ 22“,”warmestSwim“:”15“,”coldestSwim“:”15“}

但是如果我尝试通过mongoose返回总是一个空数组[]我已经有一些聚合函数运行良好,但不知道为什么那个不起作用。

	activities.aggregate([
		{ $match : { 'organizer': userId } },
		{ $group : { 
			_id : "$organizer",  
			totalSwims: { $sum : 1 }, 
			longestSwim :  { $max: "$distance" }, 
			moreDistanceSwim :  { $max: "$duration" }, 
			warmestWaterSwim :  { $max: "$activityWeather.waterTemperature" }, 
			coldestWaterSwim :  { $min: "$activityWeather.waterTemperature" }, 
			warmestSwim :  { $max: "$activityWeather.temperature" }, 
			coldestSwim :  { $min: "$activityWeather.temperature" }
		} } ]
	 , function(err, result){
	 	if (err) {
	 		console.error('Problem %s', err);
	 		return next(err);
	 	} else {
	 		console.error('Result %j', result);
	 		return next(null, result);
	 	}
	 });

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:2)

很抱歉,在发布之前搜索了一段时间没有任何相关结果我终于明白了。它接缝,就这种情况而言,我需要确保使用ObjectId方法的id而不是只发送一个字符串。

var ObjectID = require("mongodb").ObjectID;
activities.aggregate([
    { $match : { 'organizer': ObjectID(userId) } },