Node.js: Xóa bộ sưu tập khỏi cơ sở dữ liệu (Drop Collection)


Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên

Thả bộ sưu tập (Drop Collection)

Bạn có thể xóa một bộ sưu tập trong MongoDB, bằng cách sử dụng phương thức drop().

Phương thức drop() nhận một hàm gọi lại có chứa đối tượng lỗi và tham số kết quả trả về true nếu bộ sưu tập đã được loại bỏ thành công, nếu không nó trả về false.

var { MongoClient } = require('mongodb-legacy');
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
 
var dbo = client.db("mydb");
  dbo.collection("customers").drop(function(err, res) {
    if (err) throw err;
    if (res) console.log("Collection deleted");
    client.close();
  });
});

Với Mongoose

const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/mydb";
const { Schema } = mongoose
const schema = new Schema({name: "string", address: "string"})
const userinfo = mongoose.model("userinfo", schema, "customers")

mongoose.connect(url, function(err) {
  if (err)
throw err;
  userinfo.collection.drop(function(err, res){
    if (err) throw err;
    if (res) console.log("Collection deleted");
    mongoose.connection.close();
  });
});

Kết quả

Collection deleted 

db.dropCollection()

Ngoài ra, chúng ta còn cách khác để thả bộ sưu tập

var { MongoClient } = require('mongodb-legacy');
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
 
var dbo = client.db("mydb");
  dbo.dropCollection("customers", function(err, res) {
    if (err) throw err;
    if (res) console.log("Collection deleted");
    client.close();
  });
});

Với Mongoose

 const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/mydb";

mongoose.connect(url, function(err) {
  if (err) throw err;
  mongoose.connection.dropCollection("customers", function(err, res){
    if (err) throw err;
    if (res) console.log("Collection deleted");
    mongoose.connection.close();
  });
});

Kết quả

Collection deleted 

» Tiếp: Bắt đầu
« Trước: DROP TABLE và IF EXISTS
Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên
Copied !!!