Node.js MongoDB 删除集合
删除集合
通过使用 drop() 方法,可以删除在 MongoDB 中调用的表或集合。
drop() 方法接受一个回调函数,其中包含 error 对象和 result 参数,如果成功删除集合,则返回 true,否则返回 false。
实例
Delete the "customers" table:
var MongoClient = require('mongodb').MongoClient;var url = "mongodb://localhost:27017/";MongoClient.connect(url, function(err, db) {if (err) throw err;var dbo = db.db("mydb");dbo.collection("customers").drop(function(err, delOK) {if (err) throw err;if (delOK) console.log("Collection deleted");db.close();});});
将上述代码保存在名为 "demo_drop.js" 的文件中,然后运行该文件:
运行 "demo_drop.js"
C:\Users\ Your Name >node demo_drop.js
结果如下:
Collection deleted
db.dropCollection
您还可以使用 dropCollection() 方法删除表(集合)。
dropCollection() 方法接受两个参数:集合的名称和回调函数。
实例
使用 dropCollection() 删除 "customers" 集合:
var MongoClient = require('mongodb').MongoClient;var url = "mongodb://localhost:27017/";MongoClient.connect(url, function(err, db) {if (err) throw err;var dbo = db.db("mydb");<strong>dbo.dropCollection("customers", function(err, delOK) {</strong> if (err) throw err;if (delOK) console.log("Collection deleted");db.close();});});
将上述代码保存在名为 "demo_dropcollection.js" 的文件中,然后运行该文件:
运行 "demo_dropcollection.js"
C:\Users\ Your Name >node demo_dropcollection.js
结果如下:
Collection deleted