Tuesday 23 May 2017

What is a good alternative for distinct + find in mongoose

I'm trying to make a query that outputs documents that have a certain element, but also only have another unique element, for example:

 Temp.find({ UId: UserID }).sort({ "created_at" : -1 }).exec( function (err, data) {
    console.log(data + "     " + err);
    callback(data);
  });

}; Returns this:

{
    "updatedAt": "2017-05-23T18:18:19.000Z",
    "created_at": "2017-05-23T18:18:19.000Z",
    "UId": "58f8954c3602b80552b6f1fb",
    "value": 69,
    "SerialNumber": "IIOJOIMJ",
    "_id": "59247cebd96d5406651c791e",
    "__v": 0
  },
  {
    "updatedAt": "2017-05-23T16:34:22.000Z",
    "created_at": "2017-05-23T16:34:22.000Z",
    "UId": "58f8954c3602b80552b6f1fb",
    "value": 70,
    "SerialNumber": "IIOJOIMJ",
    "_id": "5924648e56628d005ad15f0e",
    "__v": 0
  }

But i want the query to only return distinct elements, so that only one of the 2 documents is returned.
I tried to do this like this:

Temp.find({ UId: UserID }).sort({ "created_at" : -1 }).distinct('SerialNumber', function (err, data) {

    console.log(data + "     " + err);
    callback(data);
  });

but that crashes my app. How can i best solve this?

Thanks!



via Krapton

No comments:

Post a Comment