【发布时间】:2020-07-29 17:13:32
【问题描述】:
我有 2 个 URL,一个指向不同的连接字符串,另一个指向本地 MongoDB 实例。当我使用带有url1 的MongoClient 建立与MongoDB 的连接并从数据库/集合中获取所需的数据并最后将其存储在一个数组中时。
现在我想将此数组插入到 localhost MongoDB 集合中,这样做我得到MongoError: Topology is closed, please connect 错误。
app.js
var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("customer");
dbo.collection("customer_report").find({}).toArray(function(err, result) {
if (err!=null){
console.log("Connection Failed!!"+err)
}
var customerArray =[];
for(i=0;i<result.length;i++){
backupArray.push({
a: result[i].a,
b: result[i].b,
c: result[i].c,
d: result[i].d,
});
}
console.log(customerArray);
res.json({content:customerArray});
db.close();
MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) {
//Trying to establish another mongodb connection wuth new url
if (err) throw err;
var dbo = db.db("localdb");
dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db1.close();
});
});
});
});
});
如果我不关闭db.close();,那么数组数据将附加到第一个 MongoDB 集合而不是本地 MongoDB。正在寻找同时处理两个 MongoClient 的解决方案或将 customerArray 插入本地 MongoDB 集合的方法。
是否有可以将数组元素添加到本地 MongoDB 集合的解决方法?
【问题讨论】:
标签: javascript node.js mongodb express mongodb-query