You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose Populate场景下Array.push()失效问题求助

问题分析

你的代码里push()本身是有效的,问题出在异步操作的执行时机:this.populate("reviews")是异步任务,.then()里的代码会在populate完成后才执行,但如果你在.then()代码块外部同步读取allReviewsRating,此时数组还没被填充,自然为空。

解决方案

方案1:使用async/await(推荐,逻辑更清晰)

把代码改成async函数,用await等待populate完成,让后续代码在异步操作结束后再执行:

async function getReviewsRatings() {
  const allReviews = await this.populate("reviews");
  // 用map直接生成数组,比循环push更简洁
  const allReviewsRating = allReviews.reviews.map(review => review.rating);
  // 在这里使用allReviewsRating,比如打印、返回或传递给其他逻辑
  console.log(allReviewsRating);
  return allReviewsRating;
}

// 调用函数
getReviewsRatings();

方案2:在.then()内部或链式调用中使用数组

如果坚持用.then(),要确保所有依赖allReviewsRating的代码都放在.then()内部或者后续的链式调用里:

const allReviewsRating = [];
this.populate("reviews").then(function (allReviews) {
  allReviewsRating.push('1');
  for (const review of allReviews.reviews) {
    allReviewsRating.push(review.rating);
  }
  // 必须在这里或后续then里使用数组,不能在外部同步读取
  console.log(allReviewsRating);
  // 可以返回数组继续链式处理
  return allReviewsRating;
}).then(ratingArray => {
  // 后续逻辑处理ratingArray
});

补充说明

你之前给.then()的回调加async是多余的——populate完成后allReviews.reviews已经是加载好的内存数据,读取review.rating是同步操作,不需要异步处理。

内容的提问来源于stack exchange,提问作者Commoq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:02:14