node.js - 外部 API 调用后无法发布到 Mongo DB
问题描述
我正在尝试对 News API 进行 fetch 调用,并在 Mongo DB 中使用我获取的数据填充我的 Articles 集合。我有两个文件:articles.js 和 article.js。- 我的架构如下所示:
// Article.js
const ArticleSchema = new Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
description: {
type: String,
required: true
},
url: {
type: String,
required: true
},
datePublished: {
type: String,
required: true
},
source: {
type: String,
required: true
}
})
在articles.js 中,这就是我的路线的样子。我的逻辑是我进行 fetch 调用,等待 JSON 返回,然后遍历该 json 并将我需要的所有信息映射到新的故事对象。一旦我有了这些对象——我想为每个对象创建一个文章的新实例,然后将它们发布到我在 Mongo DB 中的文章集合中。
/ @route POST /articles -> adds new instance of an article to the database
router.post('/', async (req, res) => {
try {
const res = await fetch('https://newsapi.org/v2/top-headlines?country=us&category=entertainment&apiKey=63c967f7cbd84c11b263b4e4758f1693');
const data = await res.json();
data.articles.forEach(article => {
const storyData = {
title: article.title,
author: article.author,
description: article.description,
url: article.url,
datePublished: article.publishedAt,
source: article.source.name
}
// console.log(storyData)
new Article(storyData)
.save()
})
} catch (err) {
console.error(err.message)
res.status(400).json({ message: err.message })
}
})
在我的 forEach 循环之后,我得到这样的对象:
{
title: `'Matrix 4' Style "Shifted" From Original Trilogy, Says Neil Patrick Harris - Hollywood Reporter`,
author: 'Ryan Parker',
description: 'The actor, who appears in the fourth installment, called the upcoming film "ambitious."',
url: 'https://www.hollywoodreporter.com/heat-vision/matrix-4-style-shifted-from-original-trilogy-says-neil-patrick-harris',
datePublished: '2020-09-16T17:54:26Z',
source: 'Hollywood Reporter'
}
我可以使用我需要的数据获取我想要的对象,但是当我尝试调用 .save() 时,我收到类似于以下内容的验证错误:
“ValidationError:文章验证失败:作者:author
需要路径。”
我认为这可能与以下事实有关,即当我向数据库发帖时,请求应该列出“标题:req.body.title”等内容......关于什么可以做的任何想法造成这个?我的目标是在创建它们时将它们简单地发布到数据库中。谢谢!!!
解决方案
推荐阅读
- spring - PrincipalExtractor 和 AuthoritiesExtractor 没有命中
- react-native - 在组件中定义 NavBar 的右键,而不是在场景中(react-native-router-flux)
- python - 相当于Python中R的qqplot
- python-3.x - 如何使用flask检查每个文件夹是否有特定文件并使用jinja2显示结果?
- sql - 如何使用 SQL Server 创建算法
- python - Kolmogorov-Smirnov 解释两个信号之间的结果
- kubernetes - 在 Kubernetes 中,是否可以通过服务选择器中的元数据字段来引用 pod?
- css - Wordpress 主题更改样式表的顺序
- typo3 - 为什么我使用 TYPO3 V9.5 后会出现 404 错误
- maven - maven:存储库中的插件,但 mvn 没有找到它