【问题标题】:Parse json from url into mongodb将 json 从 url 解析到 mongodb
【发布时间】:2016-02-08 19:55:57
【问题描述】:

我正在尝试解析来自 url 的一些 json 数据并将其保存到我的 mongoDB 模型中。但是我似乎无法从body 正确解析 JSON。我怎样才能做到这一点?

代码

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);

【问题讨论】:

    标签: json node.js mongodb express mongoose


    【解决方案1】:

    我不确定我是否完全理解你的示例中发生了什么。

    但是如果你想从节点中的请求体中检索信息,你可以从 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(一个 url)获取数据,然后将其保存到我的新闻模型中。
    • 啊,您希望节点服务器从第三方 api 中提取吗?这可以通过请求 link 来完成
    • 我想从第三方 api 中提取数据并将对象插入到我的新闻模型中
    • json sn-p是第三方api的一个例子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2014-08-01
    • 2015-05-29
    相关资源
    最近更新 更多