Bulk upsert in MongoDB using mongoose

后端 未结 6 622
自闭症患者
自闭症患者 2020-11-27 04:53

Is there any option to perform bulk upserts with mongoose? So basically having an array and insert each element if it not exists or update it if it exists? (I am using custo

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 05:19

    await Model.bulkWrite(docs.map(doc => ({
        updateOne: {
            filter: {id: doc.id},
            update: doc,
            upsert: true
        }
    })))
    
    

    Or more verbose:

    const bulkOps = docs.map(doc => ({
        updateOne: {
            filter: {id: doc.id},
            update: doc,
            upsert: true
        }
    }))
    
    Model.bulkWrite(bulkOps)
            .then(bulkWriteOpResult => console.log('BULK update OK:', bulkWriteOpResult))
            .catch(err => console.error('BULK update error:', err))
    

    https://stackoverflow.com/a/60330161/5318303

提交回复
热议问题