nodejs授權串連mongodb

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.