Warm tip: This article is reproduced from serverfault.com, please click

javascript-在Node的GET请求之后将数据传递到MongoDB

(javascript - Pass data to MongoDB after Node's GET request)

发布于 2020-11-21 19:40:00

锻炼非常简单。我需要将http.get()调用Node'之后获得的数据移至mongoDB。我正在用 Mongoose 。我的问题是如何将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
Questioner
marcin2x4
Viewed
0
marcin2x4 2020-11-29 19:13:13

我找到了一种解决方法代码,可将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...

};