Node.js: Chèn dữ liệu vào bộ sưu tập (InsertOne và InsertMany)


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êm dữ liệu vào Collection

Để chèn một bản ghi hoặc tài liệu như nó được gọi trong MongoDB, vào một bộ sưu tập, chúng tôi sử dụng phương thức insertOne().

Tham số đầu tiên của phương thức insertOne() là một đối tượng chứa (các) tên và (các) giá trị của mỗi trường trong tài liệu bạn muốn chèn.

const { MongoClient } = require("mongodb")
const url = "mongodb://localhost:27017/"

MongoClient.connect(url, function(err, client) {
    if(err) throw err;
   
const db = client.db("mydb")
    var myobj = { name: "V1Study", address: "v1study.com" };
    db.collection("customers").insertOne(myobj, function(err, res){
        if(err)
throw err;
        console.log("1 document inserted");
        client.close();
    });
});

Với mongoose 

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

mongoose.connect(url, function(err) {
    if(err) 
throw err;
    var myobj = 
{ name: "V1Study", address: "v1study.com" };

    userinfo.create(myobj, function(err){
        if(err) 
throw err;
        console.log(
"1 document inserted");
        mongoose.connection.close();
    });
});

Thêm nhiều dữ liệu cùng lúc vào Collection

Để chèn nhiều tài liệu vào một bộ sưu tập trong MongoDB, chúng tôi sử dụng phương thức insertMany().

Tham số đầu tiên của phương thức insertMany() là một mảng các đối tượng, chứa dữ liệu bạn muốn chèn.

const MongoClient } = require("mongodb")
const url = "mongodb://localhost:27017/"

MongoClient.connect(url, function(err, client) {
    if(err) throw err;
   
const db = client.db("mydb")
    var myarr = [
        { name: 'John', address: 'Highway 71'},
        { name: 'Peter', address: 'Lowstreet 4'},

        { name: 'Amy', address: 'Apple st 652'},
        { name: 'Hannah', address: 'Mountain 21'},
    ];
    db.collection("customers").insertMany(myarr, function(err, res){
        if(err) 
throw err;
        console.log("Number of documents inserted: " + res.insertedCount);
        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;
    
var myarr = [
        { name: 'John', address: 'Highway 71'},
        { name: 'Peter', address: 'Lowstreet 4'},

        { name: 'Amy', address: 'Apple st 652'},
        { name: 'Hannah', address: 'Mountain 21'},
    ];

    userinfo.insertMany(myarr, function(err, res){
        if(err) 
throw err;
        console.log(
"Number of documents inserted: " + res.length);
        mongoose.connection.close();
    });
});

Kết quả trả về của insertMany()

{
  result: { ok: 1, n: 4 },
  ops: [
    { name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84 },
    { name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85 },
    { name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86 },
    { name: 'Hannah', address: 'Mountain 21', _id: 58fdbf5c0ef8a50b4cdd9a87 } ],
  insertedCount: 4,
  insertedIds: [
    58fdbf5c0ef8a50b4cdd9a84,
    58fdbf5c0ef8a50b4cdd9a85,
    58fdbf5c0ef8a50b4cdd9a86,
    58fdbf5c0ef8a50b4cdd9a87 ]
}

 Với Mongoose:

[
  {
    name: 'John',
    address: 'Highway 71',
    _id: new ObjectId("62f887255859a6014e4ae7f5"),
    __v: 0
  },
  {
    name: 'Peter',
    address: 'Lowstreet 4',
    _id: new ObjectId("62f887255859a6014e4ae7f6"),
    __v: 0
  },
  {
    name: 'Amy',
    address: 'Apple st 652',
    _id: new ObjectId("62f887255859a6014e4ae7f7"),
    __v: 0
  },
  {
    name: 'Hannah',
    address: 'Mountain 21',
    _id: new ObjectId("62f887255859a6014e4ae7f8"),
    __v: 0
  }

» Tiếp: Tìm dữ liệu trong bộ sưu tập (FindOne và FindAll)
« Trước: Tạo bộ sưu tập (Create 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
Copied !!!