【问题标题】:Array push is not working in array forEach - Javascript数组推送在数组 forEach 中不起作用 - Javascript
【发布时间】:2018-03-11 03:34:04
【问题描述】:

我需要从迭代 mongodb 结果创建一个新数组。这是我的代码。

const result = await this.collection.find({
  referenceIds: {
    $in: [referenceId]
  }
});

var profiles = [];

result.forEach(row => {
  var profile = new HorseProfileModel(row);

  profiles.push(profile);

  console.log(profiles); //1st log
});

console.log(profiles); //2nd log

我可以在第一个日志中看到配置文件数组的更新。但是第二个日志只打印空数组。

为什么我不能将项目推送到数组?

更新 我认为这与承诺无关。 HorseProfileModel 类只是格式化代码。

const uuid = require("uuid");

class HorseProfileModel {

    constructor(json, referenceId) {

        this.id = json.id || uuid.v4();
        this.referenceIds = json.referenceIds || [referenceId];
        this.name = json.name;
        this.nickName = json.nickName;
        this.gender = json.gender;
        this.yearOfBirth = json.yearOfBirth;
        this.relations = json.relations;
        this.location = json.location;
        this.profilePicture = json.profilePicture;
        this.horseCategory = json.horseCategory;
        this.followers = json.followers || [];
    }

}

module.exports = HorseProfileModel;

【问题讨论】:

  • @Rajesh 不,他正在将新的个人资料推送到个人资料列表中......
  • forEachArray.prototype.forEach还是MongoDB版本?
  • 不如试试游标的map()方法let profiles = result.map(r => new HorseProfileModel(r))
  • @jonasw 明白你的意思。谢谢。我不会那样评论的。

标签: javascript arrays mongodb loops foreach


【解决方案1】:
 await this.collection.find(...)

返回找到的数据数组对吗?不,那太容易了。 find 立即 返回一个光标。调用 forEach 不会调用同步 Array.forEach,而是调用 Cursor.forEach,这是异步的,我们遇到了竞争问题。解决方案是将光标承诺到其结果:

const result = await this.collection.find(...).toArray();

Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多