【发布时间】:2016-07-08 04:36:38
【问题描述】:
我无法访问我创建的对象中的数据。我对 JS 和 node 很陌生,我认为我的问题是我如何初始化变量,但我不知道。
这是我的初始化:
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var async = require('async');
var currentBoatList = [];
var BoatObjectList = [];
我有一个类来创建船的当前信息(取自数据库):
function CurrentBoatInfo(boatName) {
var name,MMSI,callSign,currentDate,positionJSON,status,speed,course;
database.collection('Vessels').find({"BoatName":boatName},{"sort":{DateTime:-1}}).toArray(function(error1,vessel) {
name = vessel[0].BoatName;
MMSI = vessel[0].MMSI;
callSign = vessel[0].VesselCallSign;
console.log(name); \\logs the boats name, so the variable is there
});
});
}
我的 db 函数可以拉出最近的船只,将它们的名称放在一个列表中,然后在另一个列表中为列表中的每个船名创建对象:
编辑:我看到我多次不必要地连接到 mongoDB,使用代码来修复它,并清除“db”变量名。
var createBoats = function() {
MongoClient.connect('mongodb://localhost:27017/tracks', function(err,database){
if (err) {return console.dir(err); }
else {console.log("connect to db");}
database.collection('Vessels').find({"MostRecentContact": { "$gte": (new Date((new Date()).getTime() - (365*24*60*60*1000)))}}).toArray(function(error,docs) { //within a year
docs.forEach(function(entry, index, array) {
currentBoatList.push(entry.BoatName); //create list of boats
BoatObjectList.push(new CurrentBoatInfo(entry.BoatName,database));
});
server();
});
});
};
最后是我的服务器代码,它只是创建了一个服务器,并且应该记录上面创建的每个对象的一些信息,但由于某种原因没有(下面的输出):
var server = function() {
http.createServer(function handler(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
console.log(BoatObjectList); //array of CurrentBoatInfo objects, prints [CurrentBoatInfo {}, CurrentBoatInfo {}, CurrentBoatInfo {}]
console.log(BoatObjectList[0].name); //prints undefined
BoatObjectList.forEach(function(entry) {
var count = 0;
for(var propertyName in entry.CurrentBoatInfo) { //nothing from here prints
console.log(JSON.stringify(propertyName));
count++;
console.log(count);
}
});
res.end();
}).listen(1337, '127.0.0.1');
};
我看到的输出是这样的:
connect to db
[ 'DOCK HOLIDAY', 'BOATY MCBOATFACE', 'PIER PRESSURE' ] //list of boats
DOCK HOLIDAY //boat names as they're being instantiated
BOATY MCBOATFACE
PIER PRESSURE
[ CurrentBoatInfo {}, CurrentBoatInfo {}, CurrentBoatInfo {} ] //list of boat objects
undefined //the name of the first boat in the object list
[ CurrentBoatInfo {}, CurrentBoatInfo {}, CurrentBoatInfo {} ]
undefined
考虑到这一点,我现在认为我的问题是 createServer 代码运行,但没有记录,然后当我访问 127.0.0.1:1337 时,它记录名称(实例化时未定义)...但是如何让 createServer 等待对象被实例化?
【问题讨论】:
标签: javascript node.js class asynccallback