I have db-conn.js where I store my db connection in a function, then I require it in the create.js file and call it.
What I want is to pass the rest of the code as a callback to it, so that firstly it connects to the database and then it does the insertion.
As I am not quite good at callbacks I don´t know how to do it. Could you please help me?
So this the db-conn.js:
var mongo = {}
/**************************************************/
mongo.doConnection = (fcallback) => {
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')
})
}
/**************************************************/
module.exports = mongo
and this is the create.js:
var mongo = require(__dirname + '/db-conn.js')
/**************************************************/
mongo.doConnection()// I am not sure what to do here
createStudent = () => {
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))
})
}