Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create or update many?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading