2014-06-05 124 views
0

我在我的项目中使用sails-mongo,我需要在嵌入式集合中执行一个查询。 我的数据是类似以下内容:用mongodb在一个sails项目中查询嵌入式集合

{ 
    "_id" : ObjectId("53906c6254f36df504e99b8f"), 
    "title" : "my post" 
    "comments" : [ 
     { 
      "author" : "foo", 
      "comment" : "foo comment" 
     }, 
     { 
      "author" : "bar", 
      "comment" : "bar comment" 
     }   
    ], 
    "createdAt" : ISODate("2014-06-05T13:10:58.365Z"), 
    "updatedAt" : ISODate("2014-06-05T13:10:58.365Z") 
} 

例如,我需要提取笔者foocomments
显然风帆还不支持此功能,所以我正在考虑使用mongodb-native的对象db来进行这种查询。
由于sails-mongo使用mongodb-native,我可以在我的sails项目中访问db对象吗?或者我需要用mongodb-native建立一个新的连接?
如果有人有更好的主意,我会很感激。谢谢

回答

3

如果您只需要做访问嵌入的评论,水线应该工作正常。只需做一个正常的findfindOne,并且评论应该可以在返回的对象上访问。

如果您需要查询评论,例如由某个作者找到与评论的帖子,你可以使用你的帆船模型类的.native()方法访问底层mongodb-native集合:

Post.native(function(err, collection) { 
    if (err) { 
     // handle error getting mongo collection 
    } 
    collection.find({'comments.author':'foo'}).toArray(function(err, results) { 
     // Do something with results 
    }); 
}); 
+0

谢谢你,运作良好 – Victor