mongodb安裝完以后是沒有用戶連接授權驗證的
在控制台直接輸入mongo進入交互模式
show dbs
use databaseName
show collections
這些基本的命令都不會有問題
############################################
給mongodb加入用戶授權驗證 -----mongo進入交互模式
use admin #切換到admin數據庫 show collections #顯示數據集 ----demo ----system.users ----system.indexes ----system.version db.system.users.find() #查看system.users里面的用戶數據 ---- db.addUser('name','pwd'); #添加一個管理員賬戶
然后打開 vi /etc/mongodb.conf
找到#auth=true 反注釋掉
然后重啟mongodb數據庫服務
sudo /etc/init.d/mongodb restart
至此,mongodb的auth配置完畢
#################################
創建nodejs應用
添加mongodb插件
npm install mongodb -save
使用
var mongodb=require('mongodb').MongoClient, url='mongo://username:password@address:port/database?authMechanism=MONGODB-CR&authSource=admin', assert=require('assert'); mongodb.connect(url,function(err,db){ assert.equal(err,null); var col=db.collection('collection-name'); col.find({}).toArray(function(err,data){ console.log(data); }) })
其中authMechanism是授權機制 這個可以通過上面的 db.system.users.find()來查看
參考文獻地址:http://mongodb.github.io/node-mongodb-native/2.2/