【问题标题】:Pass data to MongoDB after Node's GET request在 Node 的 GET 请求之后将数据传递给 MongoDB
【发布时间】:2020-11-29 19:13:13
【问题描述】:

练习非常简单。我需要将调用 Node'http.get() 后获得的数据移动到 mongoDB。我正在为此使用猫鼬。我遇到的问题是如何将 GET 结果传递给 mongoose 的方法。

关于该方法的几个问题:

  1. 是否也应该为此使用 express.js 以建立用作代理的 localhost 服务器?
  2. 从良好实践的角度来看,我目前的方法是否有效?
  3. 如何自动化整个任务?只需用 CRON 触发脚本?

目前我陷入以下困境:

示例 API 数据:

{
  activity: 'Memorize the fifty states and their capitals',
  type: 'education',
  participants: 1,
  price: 0,
  link: '',
  key: '4179309',
  accessibility: 0
}

我的 mongo 集合的结构

const mongoose = require('mongoose');

const activityapiSchema = mongoose.Schema({

  _id: mongoose.Schema.Types.ObjectId,
  activity: {type: String, required: true},
  type: {type: String, required: true},
  key: {type: Number, required: true}
});

module.exports = mongoose.model('ActivityAPI', activityapiSchema);

主代码

const https = require('https');
const mongoose = require('mongoose');

const options = new URL('https://www.boredapi.com/api/activity');

//connect to MongoDB
mongoose.connect('CONNECTION_STRING',
{
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log("MongoDb connected"))
.catch(err => console.log(err));

//obtain data using GET
https.get(options, (res) => {
  console.log('statusCode:', res.statusCode);
  //console.log('headers:', res.headers);

  res.on('data', (data) => {
    //process.stdout.write(d)
    //display returned data by API
    console.log(JSON.parse(data));
  });
})

.on('error', (err) => {
  console.error(err);
});

//passing the result into MongoDB, need help

【问题讨论】:

    标签: javascript node.js mongodb rest


    【解决方案1】:

    我找到了一个解决方法代码将GET 结果传递到下一行代码。

    //obtain data using GET
    https.get(options, (res) => {
      console.log('statusCode:', res.statusCode);
      res.on('data', (data) => {
        callback(data); //allows to reference the data in callback function below
      });
    })
    
    .on('error', (err) => {
      console.error(err);
    })
    ;
    
    //retrive data and load
    function callback(value){
       console.log(JSON.parse(value));
       let valueMod = JSON.parse(value);
    
    //next thing you want to do with the data...
    
    };
    

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2020-05-25
      • 2012-01-13
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多