【发布时间】:2020-02-26 09:07:32
【问题描述】:
我正在尝试获取 json,检查 mongodb 是否存在重复,如果不存在,则将数据插入 mongodb。
问题是循环非常快,无需等待重复检查和插入。
我在这里做错了什么?
const fetch = require('node-fetch');
var MongoClient = require('mongodb').MongoClient;
async function fetchPhotos() {
MongoClient.connect("mongodb://localhost:27017", async function (err, dbo) {
const db = dbo.db('mydb')
if (err) throw err;
for (var i = 1; i < 100; i++) {
await fetch(`domain.com/?page=${i}`)
.then(res => res.json())
.then((response) => {
response.forEach(photo => {
console.log("checking if there is duplicate: " + photo.id);
var exists = db.collection("photos").countDocuments({"id": photo.id}, {limit: 1});
if (exists === 1) {
console.log("dupl found, next!");
} else {
db.collection("photos").insertOne(photo, function (err, res) {
if (err) throw err;
console.log("1 document inserted");
});
}
});
});
}
});
}
module.exports.fetchPhotos = fetchPhotos;
【问题讨论】:
-
这能回答你的问题吗? Using async/await with a forEach loop
-
永远不要在普通的异步回调中写入
if (err) throw err;。它完全没用,并且不能被您的任何代码捕获。编写真正的错误处理。
标签: node.js mongodb loops async-await