標籤:
代碼比較通俗易懂,但是我還是在這個過程中浪費了不少時間,也算是看到了nodejs中非同步一個小坑。未來的坑還有很多,慢慢找坑填坑吧。
參考資料如下:
1、斷言模組 : https://nodejs.org/api/assert.html
2、mongodb模組:https://github.com/mongodb/node-mongodb-native
廢話不多說了,發完代碼睡覺了,有興趣的朋友可以持續關注本系列。
1 //載入nodejs中的mongodb模組 2 var MongoClient = require(‘mongodb‘).MongoClient; 3 4 //載入assert(斷言模組)參考地址:https://nodejs.org/api/assert.html 5 var assert = require(‘assert‘); 6 7 // mongodb HOST地址 test表示當前所在的資料庫 8 var url = ‘mongodb://localhost:27017/test‘; 9 //啟動mongodb服務,建立串連10 MongoClient.connect(url, function(err, db) {11 assert.equal(null, err);12 console.log("Connected correctly to server");13 14 //同步嵌套的寫法15 insertDocuments(db, function() {16 updateDocument(db, function() {17 deleteDocument(db, function() {18 findDocuments(db, function() {19 db.close();20 });21 });22 });23 });24 25 //仔細觀察同步與非同步CURD執行順序。嘗試在非同步後添加db.close(); 思考為什麼報錯。26 //非同步寫法27 // insertDocuments(db, function(){});28 // updateDocument(db, function(){});29 // deleteDocument(db, function(){});30 // findDocuments(db, function(){});31 32 33 34 35 });36 37 38 39 //下面示範CURD的操作40 var insertDocuments = function(db, callback) {41 //得到文檔集合42 var collection = db.collection(‘rover‘);43 //構造資料44 var testData = [{a:1},{a:2},{a:3}];45 //插入資料46 collection.insertMany(testData, function(err, result) {47 assert.equal(err, null);48 assert.equal(3,result.result.n);49 assert.equal(3,result.ops.length);50 console.log(‘Inserted 3 Documents into the document collections‘);51 callback(result);52 53 });54 55 }; 56 57 58 //Updating a Documents 修改操作59 var updateDocument = function(db, callback) {60 //得到文檔集合61 var collection = db.collection(‘rover‘);62 //修改文檔集合63 var update = {a:2};64 var change = {$set:{a:5555}};65 collection.updateOne(update,change, function(err, result) {66 assert.equal(err,null);67 assert.equal(1, result.result.n);68 console.log("Updated the document with the field a equal to 2");69 callback(result);70 })71 };72 73 //Delete a document 74 var deleteDocument = function(db, callback) {75 // Get the documents collection76 var collection = db.collection(‘rover‘);77 // Insert some documents78 collection.deleteOne({ a : 3 }, function(err, result) {79 assert.equal(err, null);80 assert.equal(1, result.result.n);81 console.log("Removed the document with the field a equal to 3");82 callback(result);83 });84 };85 86 //讀取資料87 var findDocuments = function(db, callback) {88 // Get the documents collection89 var collection = db.collection(‘rover‘);90 // Find some documents91 collection.find({}).toArray(function(err, docs) {92 // assert.equal(err, null);93 // assert.equal(2, docs.length);94 console.log("Found the following records");95 console.dir(docs);96 callback(docs);97 });98 };
NodeJs + mongodb模組demo