首页 > 解决方案 > 使用 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中

标签: node.jsjsonmongodbmongoose

解决方案


您应该通过将正文作为 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);
});
});

推荐阅读