从url解析json到mongodb
问题描述:
我想解析一些来自url的json数据并将其保存到我的mongoDB模型中。但我似乎无法从body
正确解析JSON。我怎样才能做到这一点?从url解析json到mongodb
代码
router.get('/news', function(req, res){
request({
method: "GET",
url: "URL",
json: true
}, function(err, response, body) {
console.log(err);
res.json(body);
var info = JSON.parse(body);
console.log(info.articles);
})
});
代码片段从API
{
"articles": [
{
"title": "this is the title",
"created": "12-09-2015",
"author": "John Doe",
"image": "http://url.com/test.jpg",
"body": "this is the body"
},
{
"title": "this is the title",
"created": "12-09-2015",
"author": "John Doe",
"image": "http://url.com/test.jpg",
"body": "this is the body"
}
]
}
新闻模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var newsSchema = new Schema({
title: String,
created: String,
author: String,
image: String,
bodyfull: String
});
module.exports = mongoose.model('news', newsSchema);
答
我不确定我是否清楚你的例子中发生了什么。
但是,如果你想在节点从请求主体获取信息,你可以从一个POST请求
所以
var News = require('newsModel'); //wherever it's located
Router.post('/news', function(req,res){
var infoToParse = req.body;
var info = JSON.parse(infoToParse);
var newsItem = new News(info);
newsItem.save(function(err){
if(err) return handleError(err)
});
}
不知道有没有什么帮助呢?我不是节点大师,但这是我做的事
我想要做的是从api(一个网址)获取数据,然后将其保存到我的新闻模型中。 –
你希望节点服务器从第三方API中拉出来吗? 这可以通过请求 [链接](https://www.npmjs.com/package/request) – pjim
我想从第三方api中提取数据并将对象插入我的新闻模型 –