【发布时间】: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