Javascript 如何通过承诺在mongo建立紧密联系?
我想在NodeJS中使用mongodb的承诺。所以,我有一些代码:Javascript 如何通过承诺在mongo建立紧密联系?,javascript,mongodb,es6-promise,Javascript,Mongodb,Es6 Promise,我想在NodeJS中使用mongodb的承诺。所以,我有一些代码: 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
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();
});
});
然后我将回调
转换为承诺
:
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”
你能帮我吗?如何解决这个问题?您可以创建一些外部变量
\u客户机
并在成功连接后将客户机
分配给它,然后您可以使用\u客户机
在最后一次回调中关闭连接
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);
});
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);
});