javascript - 在 Node 的 GET 请求之后将数据传递给 MongoDB
问题描述
锻炼非常简单。我需要将调用 Node 后获得的数据移动http.get()
到 mongoDB。我为此使用猫鼬。我遇到的问题是如何将 GET 结果传递给猫鼬的方法。
关于该方法的几个问题:
- 是否也应该为此使用 express.js 以建立用作代理的 localhost 服务器?
- 从良好实践的角度来看,我目前的方法是否有效?
- 如何自动化整个任务?只需使用 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
解决方案
我找到了一个解决方法代码将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...
};
推荐阅读
- c# - C# 中的属性内存缓存
- python - 使用熊猫的合并错误
- javascript - 将 npm 包导入 Express.js 应用程序中的公共文件夹
- colors - 重新编译 ls 命令以获取以 README_* 开头的文件的所需颜色,即用字符串扩展
- spring - 在 Spring Boot 中将唯一键映射到外键
- r - 使用带有字符列表的数据框列作为 for 循环中函数的变量名称,将结果放入变量中
- ruby-on-rails - RubyMine 在尝试运行项目时显示错误,它说找不到 rails
- java - mvn原型:使用内部maven repo生成
- python - 如何在 matplotlib/seaborn 中使用饼图填充 ndarray 图形?
- php - 表单提交后如何保留值