等待对于collection.insertMany()不能正常工作?

时间:2019-10-26 19:29:15

标签: javascript node.js mongodb mongoose

我正在尝试使用collection.insertMany()在集合中插入许多记录,并且对此进行了测试,但并非总是如此,该测试不是确定性的( await 有时有时无效)。我之所以这么认为,是因为collection.insertMany('Inserted ten rogues in collection')有时在显示空白数组的console.log(queryResult)之后不正确,这是导致我的测试有时无法通过的原因。为什么这个 await 有时工作有时却不工作?

我的测试:

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方法:

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;
}

1 个答案:

答案 0 :(得分:1)

如果您在insertMany()调用中使用了回调,则该函数将不会返回Promise,因此使用await不会执行任何操作。

假设您想在回调中使用async/await,则可以使用try/catch块进行错误检查,然后await将正常工作:

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