json - Node : saving JSON to MongoDB

标签 json node.js mongodb rest

我正在尝试从 API 获取 JSON 并将其存储到 MongoDB 数据库中。 显然,这是行不通的。我的应用程序似乎停留在我尝试将数据保存到数据库的位置。请指教该怎么做。

这是我的代码:

var express = require('express');
var router = express.Router();
var http = require('http');
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/zak", {native_parser : true});


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


var site = 'http://www.vsechnyzakazky.cz/api/v1/zakazka/?format=json&limit=2';


function getData(cb) {

    http.get(site, function(res) {
        // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
        res.setEncoding('utf8');

        // incrementally capture the incoming response body
        var body = '';
        res.on('data', function(d) {
            body += d;
        });

        // do whatever we want with the response once it's done
        res.on('end', function() {
            try {
                var parsed = JSON.parse(body);
            } catch (err) {
                console.error('Unable to parse response as JSON', err);
                return cb(err);
            }

            // pass the relevant data back to the callback
            cb(
                parsed.objects
               );
        });
    }).on('error', function(err) {
        // handle errors with the request itself
        console.error('Error with the request:', err.message);
        cb(err);
    });

}

function writeData (data, allGood){     

// couple of visual checks if all looking good before writing to db
console.log('writing');
console.log(typeof data);
console.log(data);

db.collection('zakazky').save(data, function(error, record){
if (error) throw error;
console.log("data saved");

});
}

function allGood(){console.log('all done');}

getData(writeData);

// ---------------------
module.exports = router;

最佳答案

您正在调用 save() 而不是 insert()。更改此部分,它将起作用:

// this should call insert, not save
db.collection('zakazky').insert(data, function(error, record){
    if (error) throw error;
    console.log("data saved");
});

关于json - Node : saving JSON to MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121186/

相关文章:

java - 在JAVA中合并两个JSONArray到JSONObject中

node.js - 异步编程如何在单线程编程模型中工作?

javascript - 递归 javascript 函数 - 失控

java - mongodb聚合长于不同

c# - 将 JSON 字符串转换为 JSON 对象 c#

javascript - 使用 HTML5 视频及时移动覆盖内容

node.js - TypeError : dest. 不是一个函数

mongodb - 在 Mongo C-Driver 中按子字段排序

javascript - 如何将变量传递给 Mongoose "findByIdAndUpdate"

javascript - 将 JSON 加载到 Highcharts 饼图中