【问题标题】:Unable to add array data to MongoDB collection无法将数组数据添加到 MongoDB 集合
【发布时间】: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


    【解决方案1】:

    在您的第二个 mongo 连接块中,我认为您想要

    var dbo = db.db("localdb");

    成为

    var dbo = db1.db("localdb");

    【讨论】:

    • 成功了!糟糕的是,我完全忽略了这种可能性,始终专注于我们是否可以让两条路线指向直接 uri。
    【解决方案2】:

    您是否确保这些凭据在控制台命令中有效?在尝试在脚本中使用它们之前,您是否确保通过控制台的最后一个连接已关闭?

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多