gpt4 book ai didi

json - Node : saving JSON to MongoDB

转载 作者:可可西里 更新时间:2023-11-01 09:43:59 26 4
gpt4 key购买 nike

我正在尝试从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com