我正在创建一个简单的应用来学习Meteor,并且无法理解如何正确查询数据库。更改数据结构后,我现在在模板中获取[object Object]而不是最初显示的信息。 DB和API调用似乎正常工作。我认为这与我的Session变量或辅助函数有关。
以下是代码:
在客户端:
FiledRoutes = new Meteor.Collection('filedRoutes');
Template.routesTemplate.helpers({
filedRoutes: function() {
return FiledRoutes.find();
}
});
Deps.autorun(function() {
Meteor.subscribe('filedRoutes', Session.get("origin"), Session.get("destination"));
})
Template.airportForm.events({
"submit form": function(event) {
event.preventDefault()
var origin = $('#origin').val();
var destination = $('#destination').val();
Session.set('origin', $('#origin').val());
Session.set('destination', $('#destination').val());
Meteor.call("callFltAware", origin, destination, function (e, result) {
if (!e && result) {
console.log(result.data.RoutesBetweenAirportsExResult.data);
}
});
}
})
在服务器上:
FiledRoutes = new Meteor.Collection('filedRoutes');
Meteor.publish('filedRoutes', function(origin, destination) {
return FiledRoutes.find({airports: {origin: origin, destination: destination}});
})
Meteor.startup(function() {
// code to run on server at startup
});
var url = "http://flightxml.flightaware.com/json/FlightXML2/";
var username = "user";
var apiKey = "pass";
Meteor.methods({
callFltAware: function(origin, destination) {
this.unblock()
try {
var result = HTTP.call("GET", url + 'RoutesBetweenAirportsEx', {
auth: "user:pass",
params: {
origin: origin,
destination: destination,
howMany: 15,
offset: 0,
maxDepartureAge: "10 days",
maxFileAge: "30 days"
}
});
var r = result.data.RoutesBetweenAirportsExResult.data;
for (var i = 0; i < r.length; i++) {
var route = {
airports: {
origin: origin,
destination: destination
},
route: {
route: r[i].route,
filedAltitude_max:
r[i].filedAltitude_max,
filedAltitude_min: r[i].filedAltitude_min
}
}
FiledRoutes.insert(route);
}
return result
} catch (e) {
console && console.log && console.log('Exception calling', url)
throw e
}
}
})
我正在获取[object Object]的模板:
<template name="routesTemplate">
<div class="filedRoute">
{{#each filedRoutes}}
{{>route}}
{{/each}}
</div>
<template name="route">
<div class="route">
<li>{{route}}</li>
</div>
</template>
在将原点和目的地放在一个对象中之前,这是正常的。
答案 0 :(得分:1)
问题在于:
在模板中,您正在打印route
:
<template name="route">
<div class="route">
<li>{{route}}</li>
</div>
</template>
这是一个javascript对象(json文档),如:
airports: {
origin: origin,
destination: destination
},
route: {
route: r[i].route,
filedAltitude_max: r[i].filedAltitude_max,
filedAltitude_min: r[i].filedAltitude_min
}
要访问文档的属性(字段),您需要在模板中引用它们。例如,这将工作并打印出正确的字符串:
<template name="route">
<div class="route">
<li>
From {{route.airports.origin}} to {{route.airports.destination}}<br/>
<i>Altitude between {{route.route.filedAltitude_min}} and {{route.route.filedAltitude_max}}</i>
</li>
</div>
</template>
如您所见,您需要分解对象并单独访问每个密钥。
您之前可能有String
,当您在应用上迭代创建更丰富的路线文档时,您将其更改为文档,因此Object
类型。