2014-09-24 47 views
0

這是我的匯聚管道:的ObjectId和聚集沒有返回

db.articles.aggregate([ { '$match': { _id: ObjectId('5422d579466673f01a84c82f') } }, 
    { '$unwind': '$comments' }, 
    { '$project': 
    { content: '$comments.content', 
     author: '$comments.author', 
     created_at: '$comments.created_at', 
     _id: '$comments._id', 
     article: '$_id' } }, 
    { '$skip': 0 }, 
    { '$limit': 15 }, 
    { '$match': {} } ]) 

這將返回:

/* 0 */ 
{ 
    "result" : [ 
     { 
      "_id" : ObjectId("5422d5a9466673f01a84c830"), 
      "created_at" : ISODate("2014-09-24T14:31:05.644Z"), 
      "article" : ObjectId("5422d579466673f01a84c82f") 
     }, 
     { 
      "_id" : ObjectId("5422d5b4466673f01a84c831"), 
      "content" : "foo", 
      "created_at" : ISODate("2014-09-24T14:31:16.606Z"), 
      "article" : ObjectId("5422d579466673f01a84c82f") 
     } 
    ], 
    "ok" : 1 
} 

這種運作良好,使用Robomongo。我的代碼的NodeJS:

pipelines = [ 
    { 
    $match: {_id: id} 
    }, 
    { 
    $unwind: "$#{@location}" 
    }, 
    { 
    $project: project 
    }, 
    { 
    $skip: query.skip or query.offset or 0 
    }, 
    { 
    $limit: query.limit or 15 
    }, 
    if query.sort then { 
    $sort: if query.sort and query.sort[0] is '-' 
     obj = {} 
     obj[query.sort.substring(1)] = -1 
     obj 
    else if query.sort 
     obj = {} 
     obj[query.sort] = 1 
     obj 
    }, 
    { 
    $match: match 
    } 
] 

@model.aggregate _.compact(pipelines), (err, result) -> 
    if err then return deferred.reject err 
    deferred.resolve result 

id是這樣(model.schema.paths._id.options.type)(query.article)(因爲我沒有獲得貓鼬,只有模型

發送的管道是這樣的:

[ { '$match': 
    { _id: 
     { path: '5422d579466673f01a84c82f', 
      instance: 'ObjectID', 
      validators: [], 
      setters: [], 
      getters: [], 
      options: undefined, 
      _index: null } } }, 
    { '$unwind': '$comments' }, 
    { '$project': 
    { content: '$comments.content', 
     author: '$comments.author', 
     created_at: '$comments.created_at', 
     _id: '$comments._id', 
     article: '$_id' } }, 
    { '$skip': 0 }, 
    { '$limit': 15 }, 
    { '$match': {} } ] 

如果我只是將id設置爲一個字符串(沒有ObjectId構造函數),它也不起作用。如果我刪除第一個流水線($match),它的工作原理是(但我希望它與此流水線)。我很清楚。

回答

1

好問題來自我創建id的方式。這工作:

id = model.base.Types.ObjectId(...);