Nodejs:使用Mongodb儲存和提供後端CRD服務

RecoReco發表於2018-08-14

本文會把一個物件todo物件(有屬性{id,name})儲存到Mongodb,做查詢刪除的測試(Create Remove Delete = CRD)。這個測試包括使用Mongodb Shell,使用CallBack古典風格的訪問程式碼,以及使用Await/Async的現代風格的程式碼。完成這個這個驗證後,就可以掌握最初步的Mongodb了。

我使用的Nodejs是10.7 。作業系統環境為Mac OS X High Sierra。

準備環境

安裝和執行Mongodb Daemon

brew install mongodb
mongodb
複製程式碼

訪問驗證

首先執行Mongodb Shell:

mongo
複製程式碼

輸入命令,查詢資料庫清單:

> show dbs
local           0.000GB
複製程式碼

建立一個資料庫

use todos
複製程式碼

(若database不存在,則會建立一個,此時若不做任何操作直接退出,則MongoDB會刪除該資料庫)

db.todos.insert({id:1,name:"reco"})
db.todos.insert({id:2,name:"rita"})
複製程式碼

查詢 :

db.todos.find()

{ "_id" : ObjectId("5b727c0846b6c71a98d3af52"), "id" : 1, "name" : "reco" }
{ "_id" : ObjectId("5b727c7046b6c71a98d3af53"), "id" : 2, "name" : "reta" }
複製程式碼

刪除記錄:

db.todo.remove({id:1})
複製程式碼

刪除資料庫

db.todo.drop()
複製程式碼

使用nodejs方式訪問Mongodb

使用nodejs執行類似Shell對物件的CRD,程式碼如下:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/todos";
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  var dbo = db.db("todos");
  // var myobj = { id: 1, name: "reco" };
  // dbo.collection("todo").insertOne(myobj, function(err, res) {
  //   if (err) throw err;
  //   console.log("1 document inserted");
  //   db.close();
  // });
   var myobj = [
    { id: 1, name: 'reco'},
    { id: 2, name: 'rita'},
  ];
  dbo.collection("todo").insertMany(myobj, function(err, res) {
    if (err) throw err;
    console.log("Number of documents inserted: " + res.insertedCount);
    dbo.collection("todo").find({}).toArray(function(err, result) {
	    if (err) throw err;
	    console.log(result);
	      var myquery = { id: 1 };
		  dbo.collection("todo").deleteMany(myquery, function(err, obj) {
		    if (err) throw err;
		    console.log("document deleted");
		    db.close();
		  });
	  });    
  });
})
複製程式碼

程式碼非常簡單,無需更多解釋。此程式碼使用了mongodb模組,需要首先安裝:

npm init -y
npm i mongodb --save
複製程式碼

然後使用node index.js執行即可看到效果:

Database created!
Number of documents inserted: 2
[ { _id: 5b72ab9e3245f169ef5f43d2, id: 1, name: 'reco' },
  { _id: 5b72ab9e3245f169ef5f43d3, id: 2, name: 'rita' } ]
document deleted
複製程式碼

利用高階非同步特性

使用Await/Async特性,可以有效的減少程式碼中的回撥地獄現象。同樣的功能,可以使用這樣的程式碼:

const MongoClient = require('mongodb').MongoClient;
const connectionString = 'mongodb://localhost:27017';
(async () => {
    const client = await MongoClient.connect(connectionString,
        { useNewUrlParser: true });
    const dbo = client.db('todos');
    try {
       var res = await dbo.collection('todo').insertMany(
       	[{id:1,name:"reco"}, {id:2,name:"rita"}]);
       console.log("Number of documents inserted: " + res.insertedCount);
       var r = await dbo.collection("todo").find().toArray()
       console.log(r);
       var myquery = { id: 1 };
	   var r = await dbo.collection("todo").deleteMany(myquery)
	   console.log("document deleted");
    }
    finally {
        client.close();
    }
})().catch(err => console.error(err));
複製程式碼

執行此程式碼,輸出如下:

Number of documents inserted: 2
[ { _id: 5b72ae8a1c674a6ac1c5aa6e, id: 1, name: 'reco' },
  { _id: 5b72ae8a1c674a6ac1c5aa6f, id: 2, name: 'rita' } ]
document deleted複製程式碼

相關文章