2014-09-24 41 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(...);