2

So I've looked around for .distinct function in waterline 0.10.x and have failed to find one, after looking on Stack Overflow I have found this...

How to extract distinct values from a mongo database using Waterline and Sails.js (version 0.10)?

Which ALMOST solved my problem.

So I tried looking at the native mongodb documentation and found that I can do this...

db.dogs.distinct('breed', { owner: ObjectId('123456') })

Which returns the distinct breeds that ObjectId('123456') has.

But this doesn't work...

Dog.native(function (err, collection){ 
    collection.distinct('breed', { owner: '123456' }, function (err, breeds){
        console.log(breeds);
    });
});

This gives me an empty array.

I think the problem is that the .native function for Waterline doesn't understand when to cast the given string into an ObjectId and the Waterline documentation is still under-documented.

How would I get the distinct values with a query?

Community
  • 1
  • 1
Daniel Dye
  • 41
  • 4
  • So you did pretty much nail it. So then why not just do that? I also hope that you are just "abstracting" here because clearly "123456" is not going to be a valid `ObjectID` value. – Neil Lunn Mar 02 '15 at 09:14
  • I was abstracting. I was hoping that that would be known, sorry. I should have been more explicit about it. I found the solution, my problem was that my sails-mongo was version 0.10.4. sails-mongo 0.10.5 introduced a function that resolves the problem. I'll post an answer below. – Daniel Dye Mar 03 '15 at 06:26

1 Answers1

2

I found the solution.

sails-mongo v0.10.5 introduces the function used in the result.

Which can be seen here: https://github.com/balderdashy/sails-mongo/pull/215

The working code is as follows:

Dog.native(function (err, collection){
    collection.distinct('breed', {
        owner: Owner.mongo.objectId("123456")
    }, function (err, breeds){
        console.log(breeds);
    });
});

The Model.mongo.objectId function was introduced in sails-mongo 0.10.5.

Daniel Dye
  • 41
  • 4