准备
npm install mongodb /*安装mongodb模块*/
一些mongodb命令
show dbs //展示所有数据库
use db //使用该数据库,未创建则直接创建
db.documents.drop() //删除该collection中所有数据(或者使用.remove()通过条件删除)
db.documents.find() //查询该collection中所有数据
连接mongodb
/*app.js*/
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
/*assert模块用于编写程序的单元测试用例*/
// Connection URL
var url = 'mongodb://localhost:27017/elys';/*请求url*/
// 通过mongodb提供的connect方法来连接数据库
MongoClient.connect(url, function(err, db) { /*这里的db便是连接成功的mongodb*/
assert.equal(null, err);/*表达式不符合时输出err*/
console.log("Connected correctly to server");
db.close();
});
插入数据
/*新增一个用于插入数据的方法*/
var insertDocuments = function (db, callback){
var collection = db.collection('documents')/*获取collection*/
collection.insertMany([/*操作语句*/
{a:1}, {a:2}, {a:3}/*提供的数据*/
], function(err, result){/*回调*/
assert.equal(err, null)
assert.equal(3, result.result.n) /*检查结果行为等(是不是真的3个)*/
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result) /*返回结果*/
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*调用该方法*/
insertDocuments(db, function(){
db.close();
})
//...
更新数据
var updateDocument = function (db, callback){
var collection = db.collection('documents')
collection.updateOne({ a: 2 },{ $set: {b:1}}, function(err, result){
/*mongodb提供许多api,updateOne()是其中之一*/
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log("Updated the document with thie field a equal to 2")
callback(result)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*调用该方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
db.close();
})
})
//...
删除数据
var deleteDocument = function(db, callback){
var collection = db.collection('documents')
collection.deleteOne({a:3}, function(err, result){
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log("Remove the document with the field a equal to 3")
callback(result)
//console.log(result)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*调用该方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
deleteDocument(db, function(){
db.close();
})
})
})
//...
查询数据
var findDocuments = function(db, callback){
var collection = db.collection('documents')
collection.find({}).toArray(function(err, docs){
assert.equal(err, null)
assert.equal(2, docs.length)
console.log("Found the following records")
console.dir(docs)
callback(docs)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*调用该方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
deleteDocument(db, function(){
findDocuments(db, function(){
db.close();
})
})
})
})
//...
参考
https://github.com/mongodb/node-mongodb-native
未完待续