首页 > 解决方案 > Node.js:无法读取未定义的属性“then”(嵌套查询)

问题描述

我正在尝试更新具有嵌套文档的 MongoDB 集合中的字段。我必须增加一定的价值。更新查询工作得很好,但我需要将它嵌套在另一个查询中,在那里我得到当前值,所以我可以增加它。

当我使用错误的find()方法时,嵌套工作得很好。我意识到我必须使用aggregate(). 我无法让它工作,该方法由于某种原因返回未定义。我在 shell 中尝试了相同的聚合查询并且它可以工作,所以它必须对 Node.js 做一些事情

失败的功能:

static addPointsToUser(mainId, userId, pointsToAdd) {
  const db = getDb();

  function getCurrent() {
    db.collection('mycoll')
      .aggregate([
        { $match: { _id: mainId } },
        { $unwind: '$userPoints' },
        { $match: { 'userPoints._id:': userId } },
        { $group: { _id: 'userPoints._id', userPoints: { $push: '$userPoints.points' } } }
      ])
  }

  function updateNew(newPoints) {
    db.collection('mycoll')
      .updateOne(
        { _id: mainId },
        { $set: { "userPoints.$[elem].points": newPoints } },
        {
          multi: true,
          arrayFilters: [{ "elem._id": userId }]
        }
      )
  }

  return getCurrent()
    .then(result => {
      console.log(result);
      const newPoints = result.userPoints[0];
      return updateNew(newPoints)
        .then(result => {
          console.log(result);
          return result;
        })
    })
}

该文档如下所示:

{
  "_id": ObjectId("5d4048f56a895612acabe0a9"),

  // Some other fields

  "userPoints": [
    { "_id": "manualID1", "points": 80 },
    { "_id": "manualID2", "points": 90 }
  ]
}

预期的汇总结果:

{ "_id" : "manualID1", "userPoints" : [ 90 ] }

Mongo shell 给出了上面看到的结果。

实际结果:TypeError: Cannot read property 'then' of undefined

如果我记录它打印的聚合结果和空数组( [] )。

标签: javascriptnode.jsmongodb

解决方案


你的方法getCurrentupdateNew没有返回任何东西。这意味着您正在使用未定义.then()的内容,如您的错误消息所述。

之前添加一个return语句db.collection('mycoll')应该可以帮助你。


推荐阅读