node.js - 使用 nodeJS 和 mongoose 将外部 JSON 文件导入 MongoDB
问题描述
1. City.json (json-file)
{
"id": "1",
"name": "Bombuflat",
"state_id": "1"
},
{
"id": "2",
"name": "Garacharma",
"state_id": "1"
},
{
"id": "3",
"name": "Port Blair",
"state_id": "1"
}
如何使用nodeJs和mongoose将上述城市的json数据(仅一次)存储到mongoDB中
解决方案
您应该通过将正文作为 JSON 传递来编写一个 post API,并将其保存到所需的 Mongo DB 集合中。
Mongo DB 中的所有文档都将保存为 JSON。
我希望你是 node js 和 mongo db 的新手。请阅读 nodeJs 文档和 Mongo DB 文档。
这将帮助您编写您的第一个帖子 API
app.post('/city', (req, res) => {
const body = req.body();
City.save(body)
.then(response => {
console.log('saved to mongo db', response);
res.json(response);
})
.catch(error => {
console.log('error in saving to mongo db', error);
res.json(error);
});
});
推荐阅读
- vim - 从 vimscript 触发文件完成
- android - 带阴影的样条图或 3D 样条图或三次折线图
- javascript - 单击模态关闭按钮时清除表单
- javascript - 在没有 xmlhtttprequest 的 javascript 中发送 multipart/form-data
- mongodb - 我可以从托管在 firebase 动态托管上的 express 应用程序连接到 mongodb 吗?
- java - 尝试在 java 中使用 FileWriter/BufferedWriter 写入时权限被拒绝。
- c - 我书中的位域结构的大小不准确
- asp.net-core - .NET Core 托管包
- php - PHP - 如果字符串与动态数字匹配,则如果语句
- php - 服务器访问错误的存储文件夹 laravel