如何使用 mongoose 从 api 中获取数据并保存到 mongodb

How to fetch data from an api and save to mongodb using mongoose

这就是我定义架构的方式

const apiSchema = new Schema({
    entries: [{
        API: {
            type: String
        },
        Description: {
            type: String
        },
        Link: {
            type: String
        },
        Category: {
            type: String
        }

    }]
});

module.exports = mongoose.model('api', apiSchema);

这是我的控制器

const Data = require('./models/api');
p.get('/', (req, res, next) => {
    request('https://api.publicapis.org/entries', function (error, response, body) {
        var result = JSON.parse(body);
        console.log('body:', result); 
        

result = new Data({
            entries: {
                API: req.body.API,
                Desription: req.body.Desription,
                Link: req.body.Link,
                Category: req.body.Category   
            }
         })
        result.save()
            .then(result => {
                console.log('Entry saved');
            })
            .catch(err => {
                console.log(err);
            });
        
    });
    
});

当我 运行 服务器并打开指南针时,我发现只有条目数组中的对象 ID 被保存。我要将条目数组中的所有字段保存在数据库中。

您可以将抓取的数据保存如下:

  1. 先导入HTTPS模块发送HTTPS get请求
  2. 创建一个数组来保存缓冲区块
  3. 当所有块都被完全接收后,连接这些块
  4. 在 DB 上保存串联数据
//test.js controller file
const Data = require('./../database/models/test');
const https = require('https');

module.exports = (req,res)=>{
    let data =[]; //array to keep data chunks
    
    https.get('https://api.publicapis.org/entries', function (response) { //send  request to api
        
  response.on('data', d => {
    data.push(d); //get data as chunk by chunk and push them to array
  }).on('error',e=>{
      console.log(e); //
  });

  response.on('end',()=>{
//when all data chunks are received, 
// concat all buffered chunks and 
//create js object from it
   let fetchedData= JSON.parse(Buffer.concat(data).toString()); 
   console.log(fetchedData);
   let result = new Data({
    entries:fetchedData.entries // fetched data has entries array , that is data that you want to save
});
result.save() //save data to db
    .then(result => {
        console.log('Entry saved');
    })
    .catch(err => {
        console.log(err);
    });

    res.send(result);
  })

      
}) };