当数据库对所有信息都进行GET请求时,我遇到了问题。每次保存的信息量都会翻倍。
这是架构+连接:
const axios = require("axios");
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/FinalProjectDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(async () => {
console.log('connected to mongoDB-POSTS');
await getPostsFromApiAndSaveToDb(
'https://jsonplaceholder.typicode.com', 'posts',
Post
);
console.log('mongoDB populated with Data');
}).catch((err) => {
console.log(err)
})
const Schema = mongoose.Schema;
const PostSchema = new Schema(
{
userId: "String",
id: "String",
title: "String",
body: "String",
},
{
collection: "posts",
}
);
const Post = mongoose.model("Post", PostSchema);
以及我的GET请求:
const getPostsFromApiAndSaveToDb = (url, type, model) => {
return new Promise(async (resolve) => {
const response = await axios.default.get(`${url}/${type}`);
const data = response.data;
data.forEach(async (el) => {
let currentElement = new model(el);
await currentElement.save()
});
resolve();
})
}
我试图做一个IF语句,以防万一数组等于或为0时它将访问API,但我没有通过这种方式从API得到响应:
let postArray = [];
const postArrayLink = async (url) => {
const response = await axios.default.get(url)
postArray = response.data;
}
const getPostsFromApiAndSaveToDb = (url, type, model) => {
return new Promise(async (resolve) => {
const response = await axios.default.get(`${url}/${type}`);
const data = response.data;
if(postArray.length <= 0){
data.forEach(async (el) => {
let currentElement = new model(el);
await currentElement.save()
});
}
resolve();
})
}
花很多时间解决问题,欢迎任何帮助!