无法在Javascript中解析mongoose输出

时间:2015-09-16 15:57:13

标签: javascript node.js mongodb mongoose

我正在开发一个应用程序,该应用程序从mongodb数据库中获取纬度和经度列表,并将它们作为点放在谷歌地图上,但我在解析输出的JSON时遇到问题来自node.js的mongoose,这里是我用来解析JSON的代码。浏览器给我的错误是:

SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符

var jsonData = JSON.parse('http://hanky-ranky.azurewebsites.net/listbathroom');
  for (var i = 0; i < jsonData.length; i++) {
    var bathroom = jsonData[i];
    console.log(bathroom.lat);
}

这是我用来使用mongoose在node.js中生成JSON的代码

var express = require('express');
var router = express.Router();

var mongoose= require("mongoose");
//Connect to mongo DB
mongoose.connect('mongodb://test:test@ds040898.mongolab.com:40898/MongoLab-0');
var myDB = mongoose.connection;

//Error handling if conncetion fails
myDB.on('error', console.error.bind(console, 'connection error:'));
//Check if successful connection is made
myDB.once('open', function callback () {
  //console.log("MY DB Connected with Mongoose");
});

 //create an employee schema for operation with mongo
var bathroomSchema = mongoose.Schema(
{
  'name': String,
  'address' : String,
  'lat': String,
  'lng': String,
  'type': String,
},
{
  collection:'bathrooms'
}
);

// model reference
var bathrooms = mongoose.model('bathrooms', bathroomSchema);

function readBathrooms(callback)
{
  bathrooms.find({},function (error, result) {
    callback(error, result);
  });

}

router.get('/', function(req, res, next) {
  readBathrooms(function(error,result){
    if (error) {
      res.send({'result':'error'});
      console.log("Error!");
    }else {               
      //console.log(result);              
      res.render('listbathroom', {"result": result });
    }
  });
});

module.exports = router;

这里是调用显示JSON的玉文件

 !{result}

1 个答案:

答案 0 :(得分:2)

正如Kevin B向我指出的那样,我实际上并没有解析JSON,而是试图将URL解析为JSON。我用以下代码解决了我的问题

var xmlhttp = new XMLHttpRequest();
var url = "http://hanky-ranky.azurewebsites.net/listbathroom";

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var thejson = JSON.parse(xmlhttp.responseText);
    logjson(thejson);
  }
}

xmlhttp.open("GET", url, true);
xmlhttp.send();

function logjson(arr) {
  var i;
  for(i = 0; i < arr.length; i++) {
    console.log(arr[i].lat);
  }
}