Home > other >  create or update many?
create or update many?

Time:07-01

Here's my code which iterate a list of objects and, for each, check the "unique" field instrument_name and update or create the item on a MongoDB:

const dateUpdated = moment().format("YYYY-MM-DD HH:mm:ss");
for (let i = 0; i < instruments.length; i  ) {
    let instrument = instruments[i];
    instrument.dateUpdated = dateUpdated;

    let exchangeInstrument;
    try {
        exchangeInstrument = await ExchangeInstrument.updateOne({ instrument_name: instrument.instrument_name }, instrument, { upsert: true, setDefaultsOnInsert: true });
    } catch (error) {
        console.log(error);
        return;
    }
}

// model definition
import mongoose from 'mongoose';

let ExchangeInstrumentSchema = new mongoose.Schema({
    instrument_name: {
        type: String
    },
    price_decimals: {
        type: String
    },
    quantity_decimals: {
        type: String
    },
    dateUpdated: {
        type: String
    }
}, {
    collection: 'ExchangeInstruments'
})

const ExchangeInstrument = mongoose.model('ExchangeInstrument', ExchangeInstrumentSchema)
export { ExchangeInstrument }

It will create N connection on DB, slowing the process.

Can I do it "once"? Such as UpdateOrCreateMany? And, is there any "key" improvement that I can do on instrument_name field?

Thanks

CodePudding user response:

You can use bulk update to do something like:

const exchangeInstrumentBulk = ExchangeInstrumentModel.collection.initializeUnorderedBulkOp();
for (const instrument of instruments) {
    exchangeInstrument.find({ instrument_name: instrument.instrument_name }).upsert().update({$set:instrument});
}
await exchangeInstrumentBulk.execute()
  • Related