使用 meteor.js 从 MongoDB 检索数字数组
Retrieving an array of numbers from MonoDB with meteor.js
如何使用 meteor.js 从 MongoDB 集合对象中正确检索数字数组?
在代码中,我的 alert(temp)
假设输出一个相加的数字,如 5.95+5.95+5.95 = 17.85,但输出是 0[object Object][object Object][object Object][object Object][object Object][object Object][object Object]
,这意味着我没有正确地将对象转换为数字格式.请告诉我如何将对象转换成我可以加起来的数字。
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
Template.price6.events({
'click a': function () { // in my page, i clicked this multiple times to insert 3 time 5.95 into the Mongodb object.
Tasks.insert({
text: 5.95,
createdAt: new Date() // current time
});
}
});
Meteor.methods({
GetTotal: function () {
var postsArray = Tasks.find().fetch(); // it will fetch the numbers into an array according to the meteor.js doc
var temp = 0.00;
for (index = 0; index < postsArray.length; index++) {
temp += postsArray[index];
}
alert(temp);//suppose to be a number but the output result is weird 0[object][object].....
},
});
}
事件处理程序插入 Tasks
集合对象,如下所示:
{
text: 5.95,
createdAt: new Date() // current time
}
当您取回记录时,"text"(如果您只在 属性 中存储数字,这是一个误导性的名称)将是 Tasks.find().fetch()
的每个元素的键数组,所以将 .text
添加到您的代码中:
for (index = 0; index < postsArray.length; index++) {
temp += parseFloat(postsArray[index].text);
}
如何使用 meteor.js 从 MongoDB 集合对象中正确检索数字数组?
在代码中,我的 alert(temp)
假设输出一个相加的数字,如 5.95+5.95+5.95 = 17.85,但输出是 0[object Object][object Object][object Object][object Object][object Object][object Object][object Object]
,这意味着我没有正确地将对象转换为数字格式.请告诉我如何将对象转换成我可以加起来的数字。
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
Template.price6.events({
'click a': function () { // in my page, i clicked this multiple times to insert 3 time 5.95 into the Mongodb object.
Tasks.insert({
text: 5.95,
createdAt: new Date() // current time
});
}
});
Meteor.methods({
GetTotal: function () {
var postsArray = Tasks.find().fetch(); // it will fetch the numbers into an array according to the meteor.js doc
var temp = 0.00;
for (index = 0; index < postsArray.length; index++) {
temp += postsArray[index];
}
alert(temp);//suppose to be a number but the output result is weird 0[object][object].....
},
});
}
事件处理程序插入 Tasks
集合对象,如下所示:
{
text: 5.95,
createdAt: new Date() // current time
}
当您取回记录时,"text"(如果您只在 属性 中存储数字,这是一个误导性的名称)将是 Tasks.find().fetch()
的每个元素的键数组,所以将 .text
添加到您的代码中:
for (index = 0; index < postsArray.length; index++) {
temp += parseFloat(postsArray[index].text);
}