Krzysztof Kaczyński
Krzysztof Kaczyński

Reputation: 5071

await is not working correctly for collection.insertMany()?

I am trying to insert many records in my collection with collection.insertMany() and I made a test for it but unfortenly this test is not deterministic(await sometimes works sometimes not). Why I think so, because collection.insertMany('Inserted ten rogues in collection') sometimes diplayse after console.log(queryResult) which displays empty array what causes that my test sometimes fails sometimes pass. Why this await sometimes working sometimes not ?

My test:

describe('Saving records', () => {
    it('Save single record in DB', async () => {
        const warrior1 = new Warrior({
            name: 'John',
            class: 'priest',
            age: 21,
            weight: 75
        });
        await warrior1.save();
        assert(warrior1.isNew === false);
    });
    it('Save multiple records in DB', async () => {
        const tenRogues = createTenRouges();
        await Warrior.collection.insertMany(tenRogues, (err, _docs) => {
            if(err) {
                console.error(err);
            } else {
                console.log('Inserted ten rogues in collection');
            }
        });
        const queryResult = await Warrior.find({class: 'rogue'});
        console.log(queryResult);
        assert(queryResult.length === 10);
    });
});

CreateTenRogues method :

function createTenRouges() {
    const warriors = [];
    for (let i = 0; i < 10; i++) {
        warriors.push(new Warrior({
            name: 'John',
            class: 'rogue',
            age: 21,
            weight: 75
        }));
    }
    return warriors;
}

Upvotes: 1

Views: 2207

Answers (1)

user12251171
user12251171

Reputation:

If you use a callback in your insertMany() call, that function will not return a Promise, so using await there does nothing.

Assuming that you want to use async/await over callbacks, you can use a try/catch block to do your error checking and then await will work properly:

try {
  await Warrior.collection.insertMany(tenRogues);
  console.log('Inserted ten rogues in collection');
} catch (err) {
  console.error(err);
}

Upvotes: 2

Related Questions