meteor minimongo得到不一致的collection.findOne()结果

时间:2015-04-13 22:22:26

标签: javascript arrays meteor javascript-objects minimongo

我已经尝试调试一大堆代码了几个小时,把头撞到了墙上,最后将我的问题指向了代码中的一个地方,在那里分配了一个collection.findOne()的结果对变量的调用给我的数据与我在前一行中使用相同findOne()的console.log()所看到的数据不同。

prePostState = function(thisStID) {  
  console.log(Students.findOne({_id:thisStID}));  
  var stTemp = Students.findOne({_id:thisStID});  
  console.log(stTmp);  
  var testsTemp = stTmp.tests;

集合对象有一个'测试'阵列。在这个例子中,数组包含3个对象作为其元素。

虽然console.log()行都返回类似这样的内容

 Object {_id: "eXf9dqQbaemKS24Ti", name: "Student,Name", group: "none", site: "SiteName", tests: Array[3]}  

扩展每个显示不同的数据。第一个显示正确的测试:Array [3],第二个显示测试:Array [1],并且该数组中的单个元素也具有与完整数组中的匹配元素不同的数据。

---- ----更新
做了一些进一步的测试,我已经改变了一些代码。

prePostState = function(thisStID) {
  console.log(Students.find({_id:thisStID}).fetch()); //1
  var stTmp = Students.find({_id:thisStID}).fetch();
  console.log(stTmp);                                 //2
  console.log(stTmp[0].tests.length);                 //3
  for(var i = 0; i < stTmp[0].tests.length; i++) {
     console.log(stTmp[0].tests[i]);                  //4
  }  

1返回:

[Object]
  0: Object
    _id: "AqLHB8hT8GxzQ7zyD"
    group: "none"
    name: "Student,Name"
    site: "SiteName"
    tests: Array[3]

2返回:

[Object]
  0: Object
  _id: "AqLHB8hT8GxzQ7zyD"
  group: "none"
  name: "Student,Name"
  site: "SiteName"
  tests: Array[1]

3返回:

3  

4的for循环重复三次并打印出tests数组中三个对象中的每一个。

显然这意味着我可以访问我需要的数据。而不是

var testArray = stTmp.tests;

这给了我一个只有一个元素的数组,我只需要得到stTmp.tests的长度,然后使用for循环通过索引访问每个元素并将它们插入testArray变量。

所以我可以继续,但我仍然不了解我所看到的行为。我有点时间表在这一点上继续取得进展,但是当我有一些时间我可能会重新审视它并尝试以meteorpad或其他形式复制它,我可以与之共享完整的代码。

1 个答案:

答案 0 :(得分:0)

1)如果您修改Minimongo的返回值,请不要期望它继续存在。 Minimongo是专门用这种方式编写的,所以你不得不使用update运算符来更新值。

2)正确的投影API为Coll.find({..selector..}, {fields:{..projection..}})