javascript - 在循环 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");
解决方案
所以首先你必须改变
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));
推荐阅读
- r - 如何使用 ggplotGrob 和 annotation_custom 将 grob 与 ggplot 对齐?
- python - 设置 PYTHONPATH 不能修复 VS Code 中 pdb 的“指定对象不是函数或沿 sys.path 找到”错误
- django - 将 django-modeltranslation 添加到现有项目破坏测试
- django - Django 自定义登录表单不会针对 is_valid() 进行验证
- python - 根据运行时值从 tensorflow 张量中提取元素
- jquery - 在更改时附加输入表单返回默认值
- autohotkey - AutoHotKey while 循环中断
- mysql - MySQL:如何用左连接连接 2 个表(a 和 b = x1),用右连接连接 2 个(c 和 d = x2),然后内连接它们(x1 和 x2)?
- javascript - 如何通过dm给用户添加角色
- cookies - Mediawiki:Cookies