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

前端 未结 8 858
青春惊慌失措
青春惊慌失措 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:16

    you can use array.map instead use for

     const result = await Model.bulkWrite(
        documents.map(document => {
            document = {
              ...document, ...{
                last_update: Date.now(),
                foo: 'bar'
              }
            }
            return {
              updateOne: {
                filter: {document_id: document.document_id}, //filter for each item
                update: {
                  $set: document,//update whole document
                  $inc: {version: 1}//increase version + 1
                },
                upsert: true //upsert document
              }
            }
          }
        ));
    
    0 讨论(0)
  • 2020-12-05 11:18

    Hope my answer HERE helps you out. It deals with bulk upsert for an ecommerce domain asynchronously

    0 讨论(0)
提交回复
热议问题