2 years ago

#58795

test-img

dcsan

de-duping items in a mongoose list of populate IDs

I have a mongoose object which contains an array of ObjectIds, being used for population from another table. I want to be able to dedupe these. eg I have

[ '61e34f3293d9361bbb5883c7' ,'61e34f3293d9361bbb5883c7', '61e34f3293d9361bbb5883c7' ]

When i print and iterate through these they look like strings. But they also have an _id property, so I think they're somehow "populated" or at least contain references to the child table.

What's the best way to do this? I tried:

const uniqueTokens = _.uniqBy(tokens, '_id') which doesn't seem to work as _id is some kind of Object.

converting to a string will allow me to dedupe:

    const tokens = this.tokens || []
    let newTokens: string[] = []
    for (let t of tokens) {
        const text = t.toString()
        // clog.info('t', t, t._id, typeof t._id)
        if (!newTokens.includes(text)) {
            newTokens.push(text)
        }
    }

but then these aren't real Objects I can assign back to the original parent object.

    // this.tokens = newTokens
    await this.save()

I could maybe go through and re-find the objects, but that seems to be digging deeper into the hole!

Seems there must be a better way to handle these type of types...

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

I also tried using lean() on the tokens array to try and convert it back to a simple list of references, in case somehow the 'population' could be undone to help.

I'm down to creating a unique signature field for the referenced items and de-duping based on that.

arrays

mongodb

mongoose

objectid

0 Answers

Your Answer

Accepted video resources