Node.js: Tạo bộ sưu tập (Create collection)
Để tạo một bộ sưu tập trong MongoDB, hãy sử dụng phương thức createCollection():
const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017";
MongoClient.connect(url, function(err, client) {
if (err) throw err;
const db = client.db("mydb")
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
client.close();
});
});
Với Mongoose:
const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/mydb";
const { Schema } = mongoose;
mongoose.connect(url, function(err) {
if (err) throw err;
const schema = new Schema({ name: String });
try {
mongoose.model("Hello World!", schema, "customers");
console.log("Collection created!");
mongoose.connection.close();
} catch(e) {
throw e;
};
});