【发布时间】:2020-11-29 19:13:13
【问题描述】:
练习非常简单。我需要将调用 Node'http.get() 后获得的数据移动到 mongoDB。我正在为此使用猫鼬。我遇到的问题是如何将 GET 结果传递给 mongoose 的方法。
关于该方法的几个问题:
- 是否也应该为此使用 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
【问题讨论】:
标签: javascript node.js mongodb rest