[英]Cant deleteMany documents inside a MongoDB with nodejs
I want to create a script which is going to delete documents in collections but remain the collection itself (just make 0 documents inside a collection).我想创建一个脚本,它将删除 collections 中的文档,但保留集合本身(只需在集合中创建 0 个文档)。 When I run the script with node it just runs but didn't do anything at all.当我使用节点运行脚本时,它只是运行但根本没有做任何事情。 No errors.没有错误。
Code:代码:
var mongoClient = require('mongodb').MongoClient;
var url = 'mongodb+srv://username:password@cluster0-1kunr.mongodb.net/<dbname>?retryWrites=true&w=majority';
mongoClient.connect(url, { useUnifiedTopology: true }, function(err, db) {
if (err) {
console.log('Sorry unable to connect to MongoDB Error:', err);
} else {
async function deleteListingsScrapedBeforeDate() {
result = await client.db("CryptoCurrencies").collection("who")
.remove({});
console.log(`${result.deletedCount} document(s) was/were deleted.`);
await deleteListingsScrapedBeforeDate();
}
}
});
Also is there a way to have a script which is going to delete all documents in multiple collections?还有一种方法可以让脚本删除多个 collections 中的所有文档吗? Can I declare a collections like an array?我可以像数组一样声明 collections 吗?
In the above code the function deleteListingsScrapedBeforeDate()
is never actually called (also if it were called this would result in an endless recursion).在上面的代码中,function deleteListingsScrapedBeforeDate()
从未真正被调用(如果它被调用,这将导致无限递归)。 You should change this to:您应该将其更改为:
const MongoClient = require('mongodb').MongoClient;
async function deleteListingsScrapedBeforeDate(db) {
await db.collection("who").remove({});
console.log(`${result.deletedCount} document(s) was/were deleted.`);
}
(async function() {
const url = 'mongodb+srv://username:password@cluster0-1kunr.mongodb.net/<dbname>?retryWrites=true&w=majority';
const dbName = '<dbname>';
let client;
try {
client = await MongoClient.connect(url);
const db = client.db(dbName);
await deleteListingsScrapedBeforeDate(db);
} catch (err) {
console.log(err.stack);
}
if (client) {
client.close();
}
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.