如何为多个文件包含MondoDB连接

时间:2017-11-08 09:47:39

标签: node.js mongodb

我有CRUD system。这是我的create.js文件。如何使db connection可用于其余文件,而无需在每个文件中重写相同的代码。

mongo = require('mongodb').MongoClient
global.db = null
sDatabasePath = 'mongodb://localhost:27017/kea'
global.mongoId = require('mongodb').ObjectID

/**************************************************/
mongo.connect(sDatabasePath, (err, db) => {
    if (err) {
        console.log('ERROR 003 -> Cannot connect to the database')
        return false
    }
    global.db = db
    console.log('OK 002 -> Connected to the database')

    var jStudent =
        {
            "firstName": "Sarah",
            "lastName": "Jepsen",
            "age": 27,
            "courses": [
                {
                    "courseName": "Web-development",
                    "teachers": [
                        {
                            "firstName": "Santiago",
                            "lastName": "Donoso"
                        }
                    ]
                },

                {
                    "courseName": "Databases",
                    "teachers": [
                        {
                            "firstName": "Dany",
                            "lastName": "Kallas"
                        },
                        {
                            "firstName": "Rune",
                            "lastName": "Lyng"
                        }
                    ]
                },
                {
                    "courseName": "Interface-Design",
                    "teachers": [
                        {
                            "firstName": "Roxana",
                            "lastName": "Stolniceanu"
                        }
                    ]
                }
            ]
        }

    global.db.collection('students').insertOne(jStudent, (err, result) => {
        if (err) {
            var jError = { "status": "error", "message": "ERROR -> create.js -> 001" }
            console.log(jError)
        }
        var jOk = { "status": "ok", "message": "create.js -> saved -> 000" }
        console.log(jOk)
        console.log(JSON.stringify(result))
    })
})

因为这不能自行解决。它说:Cannot read property 'collection' of undefined,但我不想再重复一次sam代码。什么是solution

global.db.collection('students').find({}, { "courses.courseName": true, _id: false }).toArray((err, result) => {

    if (err) {
        var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
        console.log(jError)
    }
    var jOk = { "status": "ok", "message": "student.js -> all courses found -> 000" }
    console.log(jOk)
    console.log(JSON.stringify(result))
})

1 个答案:

答案 0 :(得分:0)

使用以下代码

为mongodb连接创建单独的文件
// External Modules
// MongoDB connection
var mongoose = require( 'mongoose' ); 

var dbURI = '127.0.0.1:27017/kea';
mongoose.connect(dbURI);

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection open to ' + dbURI);
}); 

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected'); 
});

// If the Node process ends, close the Mongoose connection 
process.on('SIGINT', function() {  
  mongoose.connection.close(function () { 
    console.log('Mongoose default connection disconnected through app 
    termination'); 
    process.exit(0); 
  }); 
}); 

通过app.js将其提供给整个应用

var db = require('./server/models/mongodb');

它会做什么,它在app start上连接到mongodb。现在,您可以在应用程序的每个位置使用mongodb连接,而无需再次运行相同的连接命令。