How to create an list of unique mongoose ObjectIds from a unsorted list of ObjectIds? How to create an list of unique mongoose ObjectIds from a unsorted list of ObjectIds? mongoose mongoose

How to create an list of unique mongoose ObjectIds from a unsorted list of ObjectIds?


You can use this snippet to get unique elements. I'm not aware of any in-build mongoose function for that (you can try the unique: true option for schema definition, but I'm not sure if that will work for you).

var unique = [], tempObj = {};objectIdsArray.forEach(function (val) {    var stringified = val.toString();    if (!tempObj[stringified]) {        unique.push(val);        tempObj[stringified] = val;    }});


I don't know that this is optimal or not, but you can use lodash uniq method to get an duplicate free array. I think this example will help you.

_.uniq([1, 2, 1]);// → [1, 2]

You can read more lodash uniq.