使用 meteor.js从 MonoDB 检索数字数组

Retrieving an array of numbers from MonoDB with meteor.js

本文关键字:检索 数字 数组 MonoDB meteor js 使用      更新时间:2023-09-26

如何使用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);
}