gpt4 book ai didi

javascript - 遍历所有集合并删除它们

转载 作者:行者123 更新时间:2023-11-30 11:29:14 24 4
gpt4 key购买 nike

我有这个代码:

exports.cleanDB = function() {
return mongoose.connection.db.dropDatabase();
};

既然那是弊端,我想遍历所有的集合,想调用

mongoose.connection.db.DateTime.remove();

在每一个上。

有人可以帮我创建带有返回语句的代码吗?

在应用程序的另一部分,我不知道如何重写类似的代码:

  exports.cleanDB = function*(req) {

yield mongoose.connection.db.dropDatabase();

最佳答案

真的看不出删除数据库有什么问题。但是如果你真的必须那么你可以循环注册的模型并执行 .remove()

例如:

// Just similating an async wrapper
(async function() {

try {

const conn = await mongoose.connect(uri,options);

// Loop all registered models
await Promise.all(
Object.entries(conn.models).map(([k,m]) => m.remove())
)

} catch(e) {
console.error(e)
}

})()

或者简单的 promise :

mongoose.connect(uri,options).then( conn => {

Promise.all(
Object.entries(conn.models).map(([k,m]) => m.remove())
).then( () => /* something */ )

})

你甚至可以做 Object.keys如果您不支持 Object.entries()

mongoose.connect(uri,options).then( conn => {

Promise.all(
Object.keys(conn.models).map(k => conn.models[k].remove())
).then( () => /* something */ )

})

或者,如果你真的必须这样做,那么深入到数据库级别并使用 .collections() 删除所有集合。来自 Db

的方法
(async function() { 

try {

const conn = await mongoose.connect(uri,options);

// Get every collection in an array
await Promise.all(
(await conn.db.collections()).map( c => c.remove() )
);

} catch(e) {
console.error(e)
}

})()

或者简单的 promise :

mongoose.connect(uri,options).then( conn => {

conn.db.collections()
.then( collections => Promise.all(
collections.map( c => c.remove() )
)
.then( () => /* something */ )

})

模型注册与否都没有关系。

所以这实际上取决于您更愿意采用哪种方法,如果您已经拥有应该处理以加载和注册每个模型的代码,那么使用已注册的模型应该就足够了。否则,使用直接驱动程序方法获取对数据库中当前所有集合的引用可确保即使模型尚未注册,它的集合仍会删除所有内容。

请注意 Db.collections()基本上是 Db.listCollections() 输出的包装版本这实际上是返回 Collection对象而不仅仅是“名称”。

关于javascript - 遍历所有集合并删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46846858/

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