Search code examples
node.jsmongodbmongoose-schema

How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?


I have an array called "doc" which contains a list, in which some of them contains same ref object id, I have to remove that duplicate, but none of the code is working because I'm filtering according to ref object id, which is in the form of object. I have to access the id inside the object and filter it according to that object id. here userId is the referance object id.

Answer.find({'blockId': questId}, (err, doc) => {
        if(doc!=null){
            userId = 0;
            userList = [];
            userIdd = 0;
            uslist = [];
            for(var i = 0; i<doc.length; i++){
                if(userId != doc[i].userId){
                    userIdList.push({'userId':doc[i].userId});
                    userId = doc[i].userId;
                }
            }
        }else{

        }
    });

Solution

  • I got a simple solution for this. if 'doc' is the array which contains duplicates.

     userIdList = [];
     userIdList = Object.values(doc.reduce((acc,cur)=>Object.assign(acc,{[cur.userId.toString()]:cur}),{}));