【问题标题】:Express and Mongodb insert same data multiple timesExpress 和 Mongodb 多次插入相同的数据
【发布时间】:2016-09-11 05:23:14
【问题描述】:

我对 Express 和 Mongodb 很陌生。我正在进行的项目要求我:

  1. 取一个包含多个url的对象
  2. 下载网址内容并保存到云存储
  3. 为每个保存的文件生成链接
  4. 将这些链接作为单独的文档保存到 Mongodb 中

传入的对象如下所示:

{
    "id" : 12345678,
    "attachments" : [ 
        {
            "original_url" : "https://example.com/1.png",
        },
        {
            "original_url" : "https://example.com/2.png",
        },
        {
            "original_url" : "https://example.com/3.png",
        }
    ]
}

最终目标是在 mongodb 上保存 3 个像这样的单独文档:

{
    "id" : 87654321,
    "some_other_data": "etc",
    "new_url" : "https://mycloudstorage.com/name_1.png"
}

我有一个这样的简单循环:

for(var i = 0; i < original_data.attachments.length; i++){

    var new_url = "https://example.com/" + i + ".png";

    download(original_url, new_url, function(new_url){

        console.log(new_url)

        new_data.new_url = new_url;

        save_new_url_to_mongodb(new_data);

    });
}

保存功能如下:

function save_new_url_to_mongodb (data, cb) {
  getCollection(collection, function (err, collection) {
    if (err) {
      return cb(err);
    }

    collection.insert(data, {w: 1, ordered: false}, function (err, result) {
      if (err) {
        return cb(err);
      }

      var item = fromMongo(result.ops);
      cb(null, item);
    });
  });
}

var download = function(original_url, new_url, callback){
  request.head(original_url, function(err, res, body){
    if(res === undefined){
        console.log(err);
    } else {

        var localUrlStream = request(original_url);
        var file = bucket.file(new_url);
        var remoteWriteStream = file.createWriteStream();
        var stream = localUrlStream.pipe(remoteWriteStream);

        stream.on('error', function (err) {
            next(err);
        });

        stream.on('finish', function(){
            callback(new_url);
        });
    }
  });
};

下载部分很好,我的云存储中有 3 个不同的图像文件。 console.log 还给了我 3 个不同的新 url。

问题是新保存的mongodb文档都有相同的new_url。有时如果原始数据中有更多的original_url,一些新的文档会保存失败。

非常感谢

【问题讨论】:

  • 还附上你的下载功能
  • @Wasiq Muhammad 包含并更新了保存功能,使其更有意义。谢谢

标签: javascript node.js mongodb express


【解决方案1】:

这是您在 for 循环中分配 new_url 的范围问题。见这里:JavaScript closure inside loops – simple practical example

一种解决方案是使用Array.Prototype.forEach,它本质上解决了范围问题,因为每次迭代都会为回调创建一个闭包

original_data.attachments.forEach(function(i) {
  var new_url = "https://example.com/" + i + ".png";

  download(original_url, new_url, function(new_url){
    console.log(new_url)
    new_data.new_url = new_url;
    save_new_url_to_mongodb(new_data);
  });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多