如何使用nodejs将json文件中的数据放在mongoDB中



我有这样的数据在我的json文件-

[{
"end_year": "",
"intensity": 6,
"sector": "Energy",
"topic": "gas",
"insight": "Annual Energy Outlook",
"url": "http://www.eia.gov/outlooks/aeo/pdf/0383(2017).pdf",
"region": "Northern America",
"start_year": "",
"impact": "",
"added": "January, 20 2017 03:51:25",
"published": "January, 09 2017 00:00:00",
"country": "United States of America",
"relevance": 2,
"pestle": "Industries",
"source": "EIA",
"title": "U.S. natural gas consumption is expected to increase during much of the projection period.",
"likelihood": 3
}]

和我想插入它在我的mongoDB使用nodeJS。

首先,非常好的问题。基本上,有很多方法可以将JSON文件导入MongoDB。

如果你的JSON文件结构遵循你的数据库模式或你想要导入的特定集合模式

1。第一个方法

您可以使用MongoDB Compass将JSON导入MongoDB数据库如果你没有MongoDB Compass,你可以从这里轻松下载

2。第二种方式

您可以使用MongoDB Compass的替代品,如Robo 3T,你可以很容易地导入JSON到Mongodb使用Robo 3T -遵循这一步一步的方式。

以上两种方法都很好,你自己决定用哪一种。

其次,如果你有一个JSON文件没有根据你的数据库模式或特定模式组织,那么你需要根据你的数据库模式组织JSON文件,然后将其导入数据库。这是一种非常简单的方法。

按此顺序:

  1. 迁移猫鼬

逻辑将是,在你的项目中使用npm或yarn安装迁移mongoose包。按照文档进行配置。然后你只需要在你的迁移文件中使用fs读取JSON文件,并构造JSON文件,并在迁移猫鼬的up函数中将查询插入数据库。

你会很容易解决这个问题

希望这对你有帮助

最新更新