Node.js và Mongodb hướng dẫn kết nối

Công Nghệ
Node.js và Mongodb hướng dẫn kết nối
Bài viết được sự cho phép của smartjob.vn Mục đích: Kết nối node js với cơ sở dữ liệu mongodb. Ở phần này hướng dẫn một số cách kết nối với cơ sở dữ liệu Mongodb và các truy vấn Mongodb. MongoDB là gì? Cơ sở dữ liệu phi quan...

Bài viết được sự cho phép của smartjob.vn

Mục đích: Kết nối node js với cơ sở dữ liệu mongodb.

Ở phần này hướng dẫn một số cách kết nối với cơ sở dữ liệu Mongodb và các truy vấn Mongodb.

Các bạn xem qua ở phần trước đã có hướng dẫn cài đặt Node.js trước khi tới phần này.Hướng dẫn nhanh phần cài đặt Mongodb.

Hướng dẫn cài đặt Mongo db phiên bản mới nhất và tool Robomongo quản lý (nó giống các tool quản lý mysql như Naviacat )

Cách cài đặt riêng từng gói .Truy cập trang chủ, download bản cài đặt: https://www.mongodb.org/downloads#production

Lưu ý: Bạn nên sử dụng hệ điều hành 64 bit, không khuyến khích sử dụng hệ điều hành 32 bit

Gói cài đặt điển hình (như ảnh chụp màn hình) là mongodb-win32-x86_64-3.2.3-signed.msi có dung lượng 93 MB

Tiếp tục cài đặt và tới finish

Sau đó cài đặt biến môi trường như sau :

Bấm tổ hợp phím Windows + R để gọi tiện ích Run, gõ systempropertiesadvanced  để vào chương trình thiết lập biến môi trường.

thêm text :    ;C:Program FilesMongoDBServer3.2bin   vào cuối bước 3

 Mở CMD và gõ lệnh : mongod -version

Hiện lên màn hình sau nếu thành công

Sau đó tạo thư mục để chứa Data base như hình sau :

Nội dung file config.txt

##store data
dbpath=C:mongodbdata

##all output go here
logpath=C:mongodblogmongo.log

Sau đó trỏ tới thư mục cài đặt mông trên ổ C: của mình đã cài đặt như đường link:

C:Program FilesMongoDBServer3.2bin

Và gõ lệnh sau :

mongod.exe --config C:mongodbconfig.txt

Sau đó gõ lệnh sau để kiểm tra version : mongodb -version

Sau đó tới thư mục sau và gõ lệnh để chạy :mongod.exe –dbpath “C:mongodbdata”

Chú ý : Từ lần sau khi muốn kết nối với Mongodb bằng Node.js hay PHP … bạn mở CMD và thự thi dòng lệnh trên

Các bạn tham khảo nội dung hướng dẫn dung Robomongo quản lý Mongodb: https://smartjob.vn/huong-dan-dung-robomongo-quan-ly-mongodb/

Tải source code tại đây:node_mongo

Tạo cấu trúc file thư mục như sau : folder : node_mongo  file : conect_smartjob_mongo.js

Mở CMD và trỏ tới thư mục chứa file conect_smartjob_mongo.js gõ lệnh :   npm install mongodb  như hình dưới

Sau đó thì thư mục sẽ xuất hiện thêm folder:node_modules  như hình vẽ

Nội dung file : conect_smartjob_mongo.js

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} 
else 
{
//HURRAY!! We are connected.
console.log('Connection established to', url);

// Get the documents collection
var collection = db.collection('zips');

// Find some state
collection.find({'state': 'MA'}).toArray
(

function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log(result);
//var result=result.length;

} else {
console.log('No document(s) found with defined "find" criteria!');
}
//Close connection
db.close();
}

);
}
});

Ở dòng 24 của file conect_smartjob_mongo.js như trên ta thấy điều kiện truyền vào lấy ra các bản ghi (theo cách nói của cơ sở dư liệu mysql ) ở đây là lấy ra các document có điều kiện là có  state bằng ‘MA‘ và hiển thị lên cửa sổ lệnh cmd qua lệnh console.log  sau đây là kết quả hiển thị được:

Ở cùng dòng đó  ta có thể thay bằng các điều kiện khác để thực hiện truy vấn như:

– collection.find( ).toArray      // lấy tất cả các kết quả trong collection

– collection.find({‘state’: ‘MA’,’pop’:9610}).toArray      // thêm 1 điều kiện query nữa

– collection.find({‘address.zipcode’: 10075}).toArray   // nếu có chứa các cặp field: value lồng trong cặp field:value

-collection.find({ pop:{$gt:9600} }).toArray    //  điều kiện lớn hơn với filed pop

-collection.find({ pop:{$lt:9600} }).toArray   // nhỏ hơn

–  collection.find( {$or: [ { “sate”: “MA” }, { ‘pop’:{ $gt:40992} } ]}).toArray   // phép toán OR

Làm tương tự và thực hiện lệnh thực thi file insert.js giống như ở trên : node insert.js file code insert.js như sau:

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} 
else 
{
//HURRAY!! We are connected. :)
console.log('Connection established to', url);

// Get the documents collection
var collection = db.collection('zips');
//Create some document
var smartjob1 = {city: 'smartjob.vn', pop: 1242, state: 'MA', loc: [-72.936114, -72.936114]};
var smartjob2 = {city: 'mang tuyen dung hang dau viet nam', pop: 3442, state: 'MA', loc: [42.182949, 42.182949]};

// Insert some users
collection.insert([smartjob1, smartjob2], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
//Close connection
db.close();
});

}
});

Chú ý dòng 27  insert dữ liệu vào qua hai biến smartjob1,smartjob2.

và file update.js  update thay đổi 1 thông số trong document

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} 
else 
{
//HURRAY!! We are connected. :)
console.log('Connection established to', url);

// Get the documents collection
var collection = db.collection('zips');
collection.update({city: 'smartjob.vn'}, {$set: {city: 'smartjob.vn2'}}, function (err, numUpdated) {
if (err) {
console.log(err);
} else if (numUpdated) {
console.log('Updated Successfully %d document(s).', numUpdated);
} else {
console.log('No document found with defined "find" criteria!');
}
//Close connection
db.close();
});
}
});

Chú ý dòng 22 thay thế 1 document có thông số city = smartjob.vn và update city = smartjob.vn2

Xóa 1 document có trường (key) citysmartjob.vn2

var mongodb = require('mongodb');

var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} 
else 
{
console.log('Connection established to', url);

// Get the documents collection
var collection = db.collection('zips');
// start 
collection.deleteOne({ city : 'smartjob.vn2' }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('xoa thanh cong');
}
//Close connection
db.close();
}); 
//end 
}
});

Ở các bài tiếp theo mình cũng giới thiệu cách kết nối Mongodb bằng node.js theo ODM  hướng đối tượng băng Mongose . Chúc các bạn thực hành thành công mọi thắc mắc các bạn có thể liên hệ qua Skype : nguyenanhdung90.

strongmindinstrongbody-expert

Bài viết gốc được đăng tải tại smartjob.vn

Có thể bạn quan tâm:

Xem thêm Jobs Developer hấp dẫn trên Station D

Bài viết liên quan

Ngành IT: Làm việc “trên mây” kiếm nhiều tiền nhất hiện nay

Ngành IT: Làm việc “trên mây” kiếm nhiều tiền nhất hiện nay

Kết quả từ cuộc khảo sát đầu năm của Station D về lương bổng của lập trình viên cho thấy nhiều thay đổi đã và đang diễn ra trong ngành IT – cuộc khảo sát tập trung vào các câu hỏi về khối lượng công việc, triển vọng cũng như...

By stationd
Đâu chỉ mỗi Bitcoin, công nghệ Blockchain còn nhiều ứng dụng hơn thế!

Đâu chỉ mỗi Bitcoin, công nghệ Blockchain còn nhiều ứng dụng hơn thế!

Khi nhắc đến blockchain , lập tức mọi người thường nghĩ ngay đến các loại tiền mã hóa, chẳng hạn như bitcoin. Tuy nhiên, blockchain lại là công nghệ tạo ra tiền mã hóa nhưng bản thân công nghệ này không phải là tiền mã hóa như cách mà chúng...

By stationd
Mock phương thức static trong Unit Test sử dụng PowerMock

Mock phương thức static trong Unit Test sử dụng PowerMock

Bài viết được sự cho phép của tác giả Nguyễn Hữu Khanh Trong bài viết này, mình sẽ hướng dẫn các bạn Mock các phương thức static trong Unit Test các bạn nhé! Nếu bạn nào chưa biết về Mock trong Unit Test thì mình có thể nói sơ qua...

By stationd