本文會把一個對象todo對象(有屬性{id,name})存儲到Mongodb,作查詢刪除的測試(Create Remove Delete = CRD)。這個測試包括使用Mongodb Shell,使用CallBack古典風格的訪問代碼,以及使用Await/Async的現代風格的代碼。完成這個這個驗證後,就能夠掌握最初步的Mongodb了。node
我使用的Nodejs是10.7 。操做系統環境爲Mac OS X High Sierra。mongodb
安裝和運行Mongodb Daemon數據庫
brew install mongodb
mongodb
複製代碼
首先執行Mongodb Shell:npm
mongo
複製代碼
輸入命令,查詢數據庫清單:異步
> show dbs
local 0.000GB
複製代碼
建立一個數據庫async
use todos
複製代碼
(若database不存在,則會建立一個,此時若不作任何操做直接退出,則MongoDB會刪除該數據庫)測試
db.todos.insert({id:1,name:"reco"})
db.todos.insert({id:2,name:"rita"})
複製代碼
查詢 :ui
db.todos.find()
{ "_id" : ObjectId("5b727c0846b6c71a98d3af52"), "id" : 1, "name" : "reco" }
{ "_id" : ObjectId("5b727c7046b6c71a98d3af53"), "id" : 2, "name" : "reta" }
複製代碼
刪除記錄:url
db.todo.remove({id:1})
複製代碼
刪除數據庫spa
db.todo.drop()
複製代碼
使用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複製代碼