如何正确地关闭我的连接蒙戈
我在与用户界面和API测试学习JavaScript / Node.js的玩弄,所以我正忙着创建一个蒙戈DB交互的API。
我写这个小js脚本来填充我的分贝有两个数据集。
我的脚本,因为它代表作品完美,但我在蒙戈日志我需要关闭连接,一旦我做注意到,但我挣扎在寻找如何做一个很好的例子还是奋力使用现有的例子适合我的剧本。
#! /usr/bin/node
//Require mongodb drivers
var mongodb = require("mongodb");
//Call test data to populate db
let movieList = require("./data/MovieList");
let actorList = require("./data/ActorList");
//Create MongoObj
var MongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017";
const dbName = "MovieDatabase";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) {
console.log(`Error - unable to connect to mongodb ${err}`);
process.exit(1);
} else {
console.log(`Connection Successful`);
}
var dbo = db.db(dbName);
if (movieList.getAllMovies !== null) {
createAndPopulateCollections(dbo, 'movies', movieList.getAllMovies)
}
if (actorList.getAllActors !== null){
createAndPopulateCollections(dbo, 'actors', actorList.getAllActors)
}
//db.close();
})
function createAndPopulateCollections(dbo, collectionName, collectionObject) {
dbo.createCollection(collectionName);
dbo
.collection(collectionName)
.insertMany(collectionObject, function(err, result) {
if (err) {
console.log(`ERROR: ${err}`);
process.exit(1);
} else {
console.log(`Success: ${result.insertedCount}`);
process.exit(0);
}
});
}
我知道有可能是与上面的脚本#问题的负载!
回答如下:如果您需要关闭您的收藏你刚才写的这条线在你的函数结束
dbo.close();