gpt4 book ai didi

dropCollection not working. Still see collections(DropCollection不工作。仍可查看收藏集)

转载 作者:bug小助手 更新时间:2023-10-28 09:44:17 25 4
gpt4 key购买 nike



The following code should drop all connections but I see that subsequent call to collections returns collections which should be empty. What am I doing wrong?

下面的代码应该删除所有连接,但我看到对集合的后续调用返回了应该为空的集合。我做错了什么?


const collectionsBeforeDrop = await db.collections();
collectionsBeforeDrop.forEach(async (c) => {
console.log(`got collection name : ${c.collectionName}`);
await db.dropCollection(c);
});
console.log(`checking after cleanup`)
const collectionsAfterDrop = await db.collections();
collectionsAfterDrop.forEach(c => {
console.log(`got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : ${util.inspect(c.collectionName)}`); //THIS CODE HITS
throw new Error("couldn't clean up after test case");
});

Output

输出


cleaning up                                                                                                                

at Object.log (test/question.test.js:61:13)

console.log
got db [object Object]

at Object.log (test/question.test.js:64:13)

console.log
truncating collections of db Questions

at Object.log (test/question.test.js:67:13)

console.log
got collection name : areas

at log (test/question.test.js:72:15)
at Array.forEach (<anonymous>)

console.log
checking after cleanup

at Object.log (test/question.test.js:75:13)

console.log
got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : 'areas'

at log (test/question.test.js:78:15)
at Array.forEach (<anonymous>)

更多回答
优秀答案推荐

You shouldn't be using async within a forEach loop, because forEach do not wait for the await.

您不应该在forEach循环中使用异步,因为forEach不等待等待。


So what happens is that your forEach loop fires multiple async calls to drop the collections, and then immediately goes to collectionsAfterDrop. So at this time, the collections are not yet dropped.

因此,发生的情况是,forEach循环触发多个异步调用以删除集合,然后立即转到Collection tionsAfterDrop。所以在这个时候,这些收藏品还没有被丢弃。


So to fix your issue, you can change your code to:

因此,要解决您的问题,您可以将代码更改为:


const collectionsBeforeDrop = await db.collections();

for (const collection of collectionsBeforeDrop) {
console.log(`got collection name : ${c.collectionName}`);
await db.dropCollection(c);
}

// will reach here only after all collections are removed

console.log(`checking after cleanup`)

const collectionsAfterDrop = await db.collections();

for (const collection of collectionsAfterDrop) {
console.log(`got collection name after claanup! THIS SHOULDN'T HAVE HAPPENED : ${util.inspect(c.collectionName)}`); //THIS CODE HITS
throw new Error("couldn't clean up after test case");
}

更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com