NodeJS:将JSON保存到MongoDB
我试图从API获取JSON并将其存储到MongoDB数据库中。 显然,它不起作用。我的应用程序似乎挂在我试图将数据保存到数据库的位置。请告诉我该怎么办 这是我的密码:NodeJS:将JSON保存到MongoDB,json,node.js,mongodb,rest,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:
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");
});
数据是否显示在数据库中?否。我实际上手动插入了一些数据,以测试我是否正确设置了数据库连接。在使用'db.zakazky.find()'时,我看到了测试数据,但不是我试图保存的
save
在这里应该可以正常工作。但是,一些MongoDB驱动程序可能希望第二个.save()
参数为。谢谢@victorkohl。Insert()确实有效。我很惊讶,也不知道为什么,因为这正是我最初尝试使用的方法,只是作为最后的手段,我才切换到save()。谢谢你的帮助!