Vig
Vig

Reputation: 143

MongoDB insertMany BulkWriteError, avoid catch if duplicate key and perform then function

I'm importing multiple items in DB calling with a cron job the following function:

async function importItems(items){
return item_schema.insertMany(items, {ordered: false})
    .then(docs => {
        const n = docs ? docs.length : 0
        docs.map((item) => {
            /* Do something */
        })
        return `New items imported ${n} / ${items.length}`
    })
    .catch(error(500, `Error importing items.`))
}

Since a few of items could be previously imported, I'm getting the BulkWriteError due to duplicate key ('item_id') that always trigger catch.

My problem is that I need to "do something" with the n new items successfully imported that I get in the docs array in then function, ignoring the catch.

Is there any way to do that? Thanks

Upvotes: 0

Views: 684

Answers (1)

Raz Luvaton
Raz Luvaton

Reputation: 3770

function importItems(items) {
    return item_schema.find({
            item_id: {
                $in: items.map((item) => item.item_id) // Check if item_id is one of the array values
            }
        })
        .then((documents) => {
            // documents is all the items that already exists
            const newItems = items.filter((item) => !documents.find((doc) => doc.item_id === item.item_id));
            return item_schema.insertMany(newItems, { ordered: false })
                .then((docs) => {
                    const n = docs ? docs.length : 0
                    docs.map((item) => {
                        /* Do something */
                    })
                    return `New items imported ${n} / ${items.length}`
                })
                .catch(error(500, `Error importing items.`));
        })
        .catch(error(500, `Error importing items.`));
}

Upvotes: 1

Related Questions