首页 > 解决方案 > 在循环 undefiend 中将数据保存到 mongoDB

问题描述

我有一个读取 XML 并将其映射到 JSON 的函数,然后这个 JSON 循环保存到 MongoDB 中。功能工作正常数据被保存但是......在我有“行保存”的地方我有这个控制台日志......我认为这个未定义是因为 mongodb save() 没有;没有要保存的 newData 正在等待它环形。一旦它记录行保存。如何摆脱不羁?你也可以请他们我如何结束这个保存循环吗?因为当它在 20-30 秒后“停止”时我再次开始保存......所以我的代码我没有结束。

undefiend
undefiend
Row Saved
Row Saved
Row Saved
undefiend
undefiend

代码:

 function FileToFetch(dir) {
    fs.readdir(dir, async function(err, files) {
      const results = [];
      const files_path = files
        .map(function(fileName) {
          return {
            name: fileName,
            time: fs.statSync(dir + "/" + fileName).mtime.getTime()
          };
        })
        .sort(function(a, b) {
          return a.time - b.time;
        })
        .map(function(v) {
          return dir + "/" + v.name;
        });
      for (let index = 0; index < files_path.length; index++) {
        const element = files_path[index];
        results.push(element);
      }

      for (let index = 0; index < results.length; index++) {
        const element = results[index];

        let asd = await readFile(element, "utf8");
        parseString(asd, async (err, result) => {
          if (err) {
            throw err;
          } else {
            if (result.test !== undefined) {
              for (
                let index = 0;
                index < result.test.length;
                index++
              ) {
                const element = result.test[index];
                const newData = new Month({

                  name3: element.$.MetaDataVersionOID,

                });
                if (newData) {
                  newData
                    .save()
                    .then(() => console.log("Row Saved"))
                    .then(err => console.log(err));
                }
              }
            }
          }
        });
      }
    });
  }
  FileToFetch("./testing");

标签: javascriptmongodbasynchronous

解决方案


所以首先你必须改变

        newData
                .save()
                .then(() => console.log("Row Saved"))
                .then(err => console.log(err));

摆脱undefined since second then 块将解决 undefined

        newData
                .save()
                .then(() => console.log("Row Saved"))
                .catch(err => console.log(err));

我真的不明白你关于如何结束保存循环的意思,但我认为你想要某种顺序行为,你可以在这个 newData 块之前添加等待关键字

        await newData
                .save()
                .then(() => console.log("Row Saved"))
                .catch(err => console.log(err));

推荐阅读