【发布时间】:2018-08-17 11:51:34
【问题描述】:
我在使用 node.js ejs 和 mongoose 在 for 循环中工作时遇到问题。我想遍历 mongodb 中的一些对象,然后遍历每个对象中的数组。我也跳过了数据库中的第一个对象,因为这是一个模板对象。我概述了下面的问题。 (为了清楚起见,我从代码中删除了 mongoose 标签)
数据库名称 = exes
对象在 mongodb 中看起来像这样:
Exe.create({
user: "Marc",
exercise: ["Exercise", "Bench Press"],
previous: [0, 0],
});
就像测试数据一样,有 3 个对象。用户始终只是一个名称,而练习和上一个(体重)是数组。我的代码如下所示。
exes.forEach(function(exercise, index){ // irritate over each object
if (index < 1){ // Ignore first object in DB
return;
}else{
exercise.user // Print username from object
for (var i = 0; i = exercise.exercise.length; i++){
exercise.exercise[i] // print [i] item from exercise array
}
}
});
这是我的代码的外观,但页面无法加载,超时后我在控制台中收到此错误。
<--- Last few GCs --->
114564 ms: Scavenge 823.4 (839.2) -> 815.5 (839.2) MB, 0.1 / 0.0 ms [allocation failure].
114611 ms: Scavenge 823.4 (839.2) -> 815.5 (839.2) MB, 0.1 / 0.0 ms [allocation failure].
114657 ms: Scavenge 823.4 (839.2) -> 815.5 (839.2) MB, 0.1 / 0.0 ms [allocation failure].
114704 ms: Scavenge 823.4 (839.2) -> 815.5 (839.2) MB, 0.1 / 0.0 ms [allocation failure].
114755 ms: Scavenge 823.4 (839.2) -> 815.5 (839.2) MB, 0.1 / 0.0 ms [allocation failure].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x5302113fa99 <JS Object>
2: /* anonymous */ [0x53021104241 <undefined>:~22] [pc=0x33b7f9be87c] (this=0x12055783d541 <JS Global Object>,exercise=0x3b15653927a9 <a model with map 0x260077d5c781>,index=1)
3: arguments adaptor frame: 3->2
4: InnerArrayForEach(aka InnerArrayForEach) [native array.js:942] [pc=0x33b7f74fdb0] (this=0x53021104241 <undefined>,bq=0x3b1565392921 <JS Function (SharedFunctionInfo 0x1a9413...
FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
1: node::Abort() [node]
2: 0x109cafc [node]
3: v8::Utils::ReportApiFailure(char const*, char const*) [node]
4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [node]
5: v8::internal::Heap::AllocateUninitializedFixedArray(int) [node]
6: v8::internal::Factory::NewUninitializedFixedArray(int) [node]
7: 0xc4bc93 [node]
8: 0x9eb29d [node]
9: v8::internal::Runtime_ArrayPush(int, v8::internal::Object**, v8::internal::Isolate*) [node]
10: 0x33b7f7062bf
Aborted
但是,如果我删除 for 循环并像这样打印出 exercise.exercise.length:
exes.forEach(function(exercise, index){ // irritate over each object
if (index < 1){ // Ignore first object in DB
return;
}else{
exercise.user // Print username from object
exercise.exercise.length // print how many objects are in the array
}
});
我确实得到了为每个对象返回的值 2。那么为什么它不在 for 循环中分配 i = 数组长度呢?任何帮助将非常感激。
提前致谢 马克
【问题讨论】:
标签: javascript node.js mongodb mongoose ejs