I'm using sails-mongo in my project and i need to execute one query in an embedded collection. My data are something like the following:
{
"_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")
}
for example, i need to extract the comments
of author foo
.
Apparently sails does not support this feature yet, so i was considering using the object db
of mongodb-native to make this kind of query.
As sails-mongo uses mongodb-native, can i have access to db object in my sails project? Or i will need build a new connection using mongodb-native?
If anyone has a better idea I'd be grateful. Thanks
If all you need to do is access the embedded comments, Waterline should work fine. Just do a normal find
or findOne
, and the comments should be accessible on the returned objects.
If you need to query the comments, e.g. to find Posts with comments by a certain author, you can access the underlying mongodb-native
collection using the .native()
method of your Sails model class:
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
});
});