【发布时间】:2015-06-19 09:32:19
【问题描述】:
我已经尝试调试一段代码几个小时了,我的头撞到了墙上,最后将我的问题定位到代码中将 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 循环重复 3 次,并打印出 tests 数组中的三个对象中的每一个。
显然,这意味着我可以访问我需要的数据。而不是
var testArray = stTmp.tests;
这给我留下了一个只有一个元素的数组,我只需要获取 stTmp.tests 的长度,然后使用 for 循环按索引访问每个元素并将它们插入到 testArray 变量中。
所以我可以继续,但我仍然不明白我看到的行为。在这一点上,我处于继续取得进展的时间线上,但是当我有时间时,我可能会重新审视它并尝试以流星垫或其他我可以共享完整代码的形式复制它。
【问题讨论】:
-
我也试过 var stTemp = Students.find({_id.thisStID}).fetch();想了一分钟,它返回了正确的数据,但是在调用了几个 Student.update() 之后,它返回了相同的不完整/过期数据。
-
发布 MeteorPad 或分享 repo,你的问题太模糊了,我在你的控制台日志上看到了拼写错误。
-
您确定它们实际上是不同的,而且不仅仅是浏览器控制台的行为异常吗?在 chrome 中,如果您使用
x = {a: {}}、console.log(x)、x.a.b = 5,然后展开console.log输出,那么您将看到b为 5,即使在 @987654333 时未设置它也是如此@。尝试将您的代码更改为console.log(JSON.stringify(...))而不仅仅是console.log(...)。 -
不,我不确定。我在别处更改了 Collection.update() ,现在我的问题已经消失了。我尝试将其还原以测试 JSON.stringify() 与仅 console.log(),但即使仅使用 console.log(),我也不再得到不完整的数组,即使 update() 恢复为我的方式以前有过。感谢 JSON.stringify() 提示,但我不知道。很抱歉,这个明显无法重现的故障不仅浪费了我的大量时间,也浪费了这里的人们的时间。
标签: javascript arrays meteor javascript-objects minimongo