0

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))
    })
}

1 Answer 1

1

When the connect is finished in db-conn.js you need to call the fcallback callback.

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

Then in create js you need to add a callback function as a parameter to mongo.doConnection(...) which will be called when the connection is finished (fcallback is called)

With this callback, you can ensure createStudent will be called when the connection is finished.

mongo.doConnection( (err, db) => {
    if(err){
      console.error("error connection to db: " + err;
      return;
    }
    createStudent = () => {
        var jStudent =
            { } ...

});
Sign up to request clarification or add additional context in comments.

3 Comments

Do I need to specify the err for the connection again when I execute mongo.doConnection? Isn´t that redundant?
no you do not. It is redundant. error-first callbacks follow a first parameter is err and second param is data, so I followed that. If you want you can even just ignore both params and do return fcallback(); in connect, and remove them in mongo.doConnection
yeah that´s what I did. ...and then in create.js I just do mongo.doConnection(createStudent)after defining createStudent(), and it works perfectly. Thank´s.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.