我想在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” 。
你能帮我吗?如何解决这个问题?
答案 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);
});