我有一台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))
})发布于 2017-11-08 19:32:38
使用以下代码为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');它将做什么,它在应用启动时连接到mongodb。现在你可以在你的应用程序中的任何地方使用mongodb连接,而不需要再次运行相同的连接命令。
https://stackoverflow.com/questions/47176366
复制相似问题