codeDragon
codeDragon

Reputation: 565

How to pass a function as a callback of another function in Node.js?

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

Upvotes: 0

Views: 75

Answers (1)

Andrew L
Andrew L

Reputation: 5486

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 =
            { } ...

});

Upvotes: 1

Related Questions