【发布时间】:2021-07-27 10:41:13
【问题描述】:
我正在尝试创建一个网站,为我个人感兴趣的球队展示几场即将举行的足球比赛。
我正在使用 forEach() 来循环遍历球队 ID 列表,并为每个球队调用一个 api 来获取他们即将到来的比赛数据并使用 mongoose save() 将其保存到 mongodb 集合中
我遇到了一个错误,即同一个文档被多次保存并以随机顺序保存,尽管我编写了代码来解决这个问题。我认为可能存在一些关于异步的基本错误,因为我仍在学习 node.js。
我们将不胜感激!
var request = require("request");
const Match = require("../models/matchSchema");
const moment = require("moment-timezone");
const team_id = [
"40", //liv
"33", //utd
"47", //tot
"49", //chel
"541", //Real
];
const newMatches = () => {
team_id.forEach((element) => {
const options = {
method: "GET",
url: "https://v3.football.api-sports.io/fixtures",
qs: {
team: element,
next: "1",
},
headers: {
"x-rapidapi-host": "v3.football.api-sports.io",
"x-rapidapi-key": <myAPIkey>,
"Content-Type": "application/json",
},
};
request(options, async (error, response, body) => {
data = JSON.parse(body);
if (error) throw new Error(error);
const newMatch = await Match.findOne({
outcomeID: data.response[0].fixture.id,
});
//to ensure the match doesnt exist
if (!newMatch) {
const newMatchCreate = await Match.create({
outcomeID: data.response[0].fixture.id,
category: "soccer",
team1: data.response[0].teams.home.name,
team2: data.response[0].teams.away.name,
timeStart: moment
.utc(data.response[0].fixture.date)
.format("MM-DD HH:mm"),
});
await newMatchCreate.save();
}
});
});
};
module.exports = newMatches;
【问题讨论】:
标签: node.js mongodb asynchronous mongoose async-await