Node.js MongoDB 创建集合
MongoDB 中的 集合 相当于 MySQL 中的表。
创建一个集合
要在 MongoDB 中创建集合,请使用 createCollection() 方法:
实例
创建名为 “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");dbo.createCollection("customers", function(err, res) {if (err) throw err;console.log("Collection created!");db.close();});});
将上述代码保存在名为 "demo_mongodb_createcollection.js" 的文件中,然后运行该文件
运行 "demo_mongodb_createcollection.js"
C:\Users\ Your Name >node demo_mongodb_createcollection.js
结果如下:
Collection created!
重要提示: 在 MongoDB 中,在获取内容之前不会创建集合!
MongoDB 会等到您插入文档后,才会真正创建集合。