简体   繁体   中英

Mongodb update multiple documents with different values

I have been trying to use updatemany with mongoose. I want to update the values in database using an array of objects.

[
            {
                "variantId": "5e1760fbdfaf28038242d676",
                "quantity": 5

            },
            {
                    "variantId": "5e17e67b73a34d53160c7252",
                    "quantity": 13
            }
            ]

I want to use variantId as filter. Model schema is:

let variantSchema = new mongoose.Schema({
    variantName: String,
    stocks: {
        type: Number,
        min: 0
    },
    regularPrice: {
        type: Number,
        required: true
    },
    salePrice: {
        type: Number,
        required: true
    }
})

I want to filter the models using variantId and then decrease the stocks.

As you need to update multiple documents with multiple criteria then .updateMany() wouldn't work - it will work only if you need to update multiple documents with same value, Try this below query which will help you to get it done in one DB call :

const Mongoose = require("mongoose");

let variantSchema = new mongoose.Schema({
    variantName: String,
    stocks: {
        type: Number,
        min: 0
    },
    regularPrice: {
        type: Number,
        required: true
    },
    salePrice: {
        type: Number,
        required: true
    }
})

const Variant = mongoose.model('variant', variantSchema, 'variant');

let input = [
    {
        "variantId": "5e1760fbdfaf28038242d676",
        "quantity": 5

    },
    {
        "variantId": "5e17e67b73a34d53160c7252",
        "quantity": 13
    }
]

let bulkArr = [];

for (const i of input) {
    bulkArr.push({
        updateOne: {
            "filter": { "_id": Mongoose.Types.ObjectId(i.variantId) },
            "update": { $inc: { "stocks": - i.quantity } }
        }
    })
}

Variant.bulkWrite(bulkArr)

Ref : MongoDB-bulkWrite

I don't think this can be done with a single Model.updateMany query. You will need to loop the array and use Model.update instead.

for (const { variantId, quantity } of objects) {
    Model.update({ _id: variantId }, { $inc: { stocks: -quantity } });
}

To run this in a transaction ( https://mongoosejs.com/docs/transactions.html ), the code should look something like this (however I have not tried or tested this):

mongoose.startSession().then(async session => {
    session.startTransaction();

    for (const { variantId, quantity } of objects) {
        await Model.update({ _id: variantId }, { $inc: { stocks: -quantity } }, { session });
    }

    await session.commitTransaction();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM