Trying to do a bulk upsert with Mongoose. What's the cleanest way to do this?

前端 未结 8 878
青春惊慌失措
青春惊慌失措 2020-12-05 10:13

I have a collection that holds documents that contains three fields: first_name, last_name, and age. I\'m trying to figure out what query in Mongoose I can use to do a bulk

8条回答
  •  眼角桃花
    2020-12-05 11:14

    Thank @maganap. I used his/her answer and reached below concise approach:

    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(console.error.bind(console, 'BULK update error:')
    

提交回复
热议问题