简体   繁体   中英

How to terminate MongoClient.connect after executing its callback?

The following code inserts a new document, {name:'r2'} , as desired.
How can it be modified to terminate?

var MongoClient = require ('mongodb').MongoClient;

MongoClient.connect ('mongodb://localhost:27017/dbA', function (err, db) {

        if (err) {

            console.log (err);

        } else {

            var collection = db.collection ('colA');
            collection.insert ({name: 'r2'});

        } // end if (err)

});

To kill it after performing the insert, I added lines after the if clause to autokill the program after the insertion is done.

var MongoClient = require ('mongodb').MongoClient;

MongoClient.connect ('mongodb://localhost:27017/dbA', function (err, db) {

if (err) {

    console.log (err);

} else {

    var collection = db.collection ('colA');
    collection.insert ({name: 'r7'});

} // end if (err)

var exec = require ('child_process').exec;
var ppath = process.argv[1];

    // trim leading path up to the last '/'
var matched = ppath.match ('.*/(.*)');
var pName = matched [1];

//console.log ('pName: ' + pName);

var killCmd = 'kill -9 `ps -ef | grep ' + pName + ' | grep -v grep  | perl -lpe ' + "'" + 's/\\w+\\s+(\\d+).*/$1/' + "'" + '`';

//console.log ('killCmd: ' + killCmd);
exec (killCmd);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM