如何通过承诺关闭mongo中的连接?

时间:2019-06-28 16:30:18

标签: javascript mongodb es6-promise

我想在NodeJS中为mongodb使用Promise。所以,我有一些代码:

const mongo = require('mongodb').MongoClient;
const config = require('./config.json');

mongo.connect(config.URI, function (err, client) {
  const db = client.db("INDFLORIST");
  const collection = db.collection('API');
  collection.insertOne({name: 'Roger'}, function (err, res) {
    if (err) throw err;
    console.log("Document inserted");
    client.close();
  });
});

然后我将callback转换为promise

const mongo = require('mongodb').MongoClient;
const config = require('./config.json');

mongo.connect(config.URI).then(client => {
    const db = client.db("INDFLORIST");
    const collection = db.collection('API');
    return collection.insertOne({name: 'Roger'});
})
.then(function(result) {
    console.log("Document inserted");
}).then(client => {
    client.close();
})
.catch(err => {
    console.error(err);
});

但是此脚本调用错误: TypeError:无法读取未定义的属性“ close”

你能帮我吗?如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以创建一些外部变量_client_,并在连接成功后将client分配给它,然后您可以使用_client_关闭上一个then回调中的连接

const mongo = require("mongodb").MongoClient;
const config = require("./config.json");
let _client_; // <-- external variable
mongo.connect(config.URI).then(client => {
    _client_ = client; // <-- assing real client to it
    const db = client.db("INDFLORIST");
    const collection = db.collection("API");
    return collection.insertOne({name: "Roger"});
}).then(function (result) {
    console.log("Document inserted");
}).then(() => {
    _client_.close(); // <-- close connection
}).catch(err => {
    console.error(err);
});

您还可以通过所有then回调将其传递

const mongo = require("mongodb").MongoClient;
const config = require("./config.json");
mongo.connect(config.URI).then(client => {
    const db = client.db("INDFLORIST");
    const collection = db.collection("API");
    return collection.insertOne({name: "Roger"}).then(() => client);
}).then(function (client) {
    console.log("Document inserted");
    return client;
}).then(client => {
    client.close();
}).catch(err => {
    console.error(err);
});