循环保存到MongoDB [英] Saving To MongoDB In A Loop

查看:89
本文介绍了循环保存到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将新记录保存到mongoDB时遇到问题.我很确定我在代码中使用的某些内容我不太了解,我希望有人可以提供帮助.

i am having trouble saving a new record to mongoDB. i am pretty sure there is something i am using in my code that i don't fully understand and i was hoping someone might be able to help.

我正在尝试将每只猫的新记录保存到mongoDB.该代码用于node.js

i am trying to save a new record to mongoDB for each of the cats. this code is for node.js

for(var x = 0; x < (cats.length - 1); x++){
    if (!blocked){
      console.log("x = "+x);
      var memberMessage = new Message();
      memberMessage.message = message.message;
      memberMessage.recipient = room[x].userId;

      memberMessage.save(function(err){
        if (err) console.log(err);

        console.log(memberMessage + " saved for "+cats[x].name);
      });
    }
  });
}

我在循环之前记录"cats"的值,并且确实获得了我期望的所有名称,所以我认为循环遍历数组将为每个循环存储一条新记录.

i log the value of "cats" before the loop and i do get all the names i expect so i would think that looping through the array it would store a new record for each loop.

似乎发生的是,当我查看数据库时,似乎只为每个循环周期保存了最后一条记录.我不知道它将如何/为什么这样做.

what seems to happen is that when i look ta the the database, it seems to have only saved for the last record for every loop cycle. i don't know how/why it would be doing that.

在此方面的任何帮助都将受到赞赏,因为我是node.js和mongoDB的新手.

any help on this is appreciated because I'm new to node.js and mongoDB.

谢谢.

推荐答案

这是因为save实际上是一个异步的I/O操作.现在,for循环实际上是同步的. 这样想:您的JS引擎按顺序执行它看到的每一行.假设这些行被一个接一个地保留在堆栈中.当涉及到save时,它会将其放在另一个堆栈上(因为这是I/O操作,因此会花费一些时间),然后继续循环的其余部分.事实证明,引擎只会在完成旧堆栈中的每一行之后才检查该新堆栈.因此,变量cats的值将是数组中的最后一项.因此,只有最后一个值被保存.

That's because the save is actually a I/O operation which is Async. Now, the for loop is actually sync. Think of it this way: your JS engine serially executes each line it sees. Assume these lines are kept one-after-another on a stack. When it comes to the save, it keeps it aside on a different stack (as it is an I/O operation, and thus would take time) and goes ahead with the rest of the loop. It so turns out that the engine would only check this new stack after it has completed every line on the older one. Therefore, the value of the variable cats will be the last item in the array. Thus, only the last value is saved.

要抗击这一悲剧,可以使用多种方法:

To fight this tragedy, you can use mutiple methods:

  1. 关闭-了解详情


关于#2的注意事项-我不是该项目的撰稿人,但与作者合作.我已经使用该库一年多了,它又快又棒!

这篇关于循环保存到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆