標籤:
mongodb安裝完以後是沒有使用者串連授權驗證的
在控制台直接輸入mongo進入互動模式
show dbs use databaseNameshow collections
這些基本的命令都不會有問題
############################################
給mongodb加入使用者授權驗證 -----mongo進入互動模式
use admin #切換到admin資料庫show collections #顯示資料集 ----demo ----system.users ----system.indexes ----system.versiondb.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:[email protected]: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/
nodejs授權串連mongodb