連線到資料庫

要從節點應用程式連線到 mongo 資料庫,我們需要 mongoose。

安裝 Mongoose 轉到應用程式的 toot 並安裝 mongoose

npm install mongoose

接下來我們連線到資料庫。

var mongoose = require('mongoose');

//connect to the test database running on default mongod port of localhost  
mongoose.connect('mongodb://localhost/test');

//Connecting with custom credentials
mongoose.connect('mongodb://USER:PASSWORD@HOST:PORT/DATABASE');

//Using Pool Size to define the number of connections opening
//Also you can use a call back function for error handling
mongoose.connect('mongodb://localhost:27017/consumers', 
                 {server: { poolSize: 50 }}, 
                 function(err) {
                    if(err) {
                        console.log('error in this')
                        console.log(err);
                        // Do whatever to handle the error 
                    } else {
                        console.log('Connected to the database');
                    }
                });