一個(gè)簡單的nodejs連接mongodb示例钓辆,來自 mongodb官方示例
1. 創(chuàng)建package.json
首先肴焊,創(chuàng)建我們的工程目錄connect-mongodb
,并作為我們的當(dāng)前目錄
mkdir connect-mongodb
cd connect-mongodb
輸入npm init命令創(chuàng)建package.json
npm init
然后蛀恩,安裝mongodb的nodejs版本driver
npm install mongodb --save
mongodb
驅(qū)動(dòng)包將會(huì)安裝到當(dāng)前目錄下的node_modules中
2. 啟動(dòng)MongoDB服務(wù)器
安裝MongoDB并啟動(dòng)MongoDB數(shù)據(jù)庫服務(wù)茂浮,可參考我之前的文章壳咕,或者M(jìn)ongoDB官方文檔
3. 連接MongoDB
創(chuàng)建一個(gè)app.js
文件顽馋,并添加以下代碼來連接服務(wù)器地址為192.168.0.243
,mongodb端口為27017
上名稱為myNewDatabase
的數(shù)據(jù)庫
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
db.close();
});
在命令行輸入以下命令運(yùn)行app.js
node app.js
4. 插入文檔
在app.js
中添加以下代碼竟稳,使用insertMany
方法添加3個(gè)文檔到documents
集合中
var insertDocuments = function(db, callback){
// get ths documents collection
var collection = db.collection('documents');
// insert some documents
collection.insertMany([
{a:1},{a:2},{a:3}
],function(err,result){
assert.equal(err,null);
assert.equal(3,result.result.n);
assert.equal(3,result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
};
insert
命令返回一個(gè)包含以下屬性的對(duì)象:
-
result
MongoDB返回的文檔結(jié)果 -
ops
添加了_id字段的文檔 -
connection
執(zhí)行插入操作所使用的connection
在app.js
更新以下代碼調(diào)用insertDocuments
方法
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
db.close();
});
});
在命令行中使用node app.js
運(yùn)行
5. 查詢所有文檔
添加findDocuments
函數(shù)
var findDocuments = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// find some documents
collection.find({}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
};
findDocuments
函數(shù)查詢了所有'documents'集合中所有的文檔他爸,將此函數(shù)添加到MongoClient.connect的回調(diào)函數(shù)中
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
insertDocuments(db, function() {
findDocuments(db, function() {
db.close();
});
});
});
6. 使用過濾條件(query filter)查詢文檔
查詢'a':3的文檔
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
7. 更新文檔
var updateDocument = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// update document where a is 2, set b equal to 1
collection.updateOne({a:2},{
$set:{b:1}
},function(err,result){
assert.equal(err,null);
assert.equal(1,result.result.n);
console.log("updated the document with the field a equal to 2");
callback(result);
});
};
updateDocument
方法更新滿足條件a為2的第一個(gè)文檔诊笤,新增一個(gè)b屬性巾陕,并將其設(shè)置為1。
將updateDocument
方法添加到MongoClient.connect
方法的回調(diào)中
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
insertDocuments(db,function(){
updateDocument(db,function(){
db.close();
});
});
});
8. 刪除文檔
var removeDocument = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// remove some documents
collection.deleteOne({a:3},function(err,result){
assert.equal(err,null);
assert.equal(1,result.result.n);
console.log("removed the document with the field a equal to 3");
callback(result);
});
};
添加到app.js
中
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
updateDocument(db, function() {
removeDocument(db, function() {
db.close();
});
});
});
});
9. 創(chuàng)建索引
索引能夠改善應(yīng)用的性能。下面你代碼在'a'屬性上添加索引
var indexCollection = function(db,callback){
db.collection('documents').createIndex({
a:1
},null,function(err,results){
console.log(results);
callback();
});
};
更新app.js
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
insertDocuments(db,function(){
indexCollection(db,function(){
db.close();
});
});
});
代碼已經(jīng)托管在碼云