首页 > 解决方案 > 在 Node 的 GET 请求之后将数据传递给 MongoDB

问题描述

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

关于该方法的几个问题:

  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

标签: javascriptnode.jsmongodbrest

解决方案


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

};

推荐阅读