【问题标题】:Node.js: Cannot read property 'then' of undefined (nested query)Node.js:无法读取未定义的属性“then”(嵌套查询)
【发布时间】:2019-12-10 01:26:20
【问题描述】:

我正在尝试更新具有嵌套文档的 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: 无法读取未定义的属性 'then'

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

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

您的方法 getCurrentupdateNew 没有返回任何内容。这意味着您在错误消息中指出的 undefined 上使用了 .then()

db.collection('mycoll') 之前添加return 语句应该对您有所帮助。

【讨论】:

  • 现在我有一个TypeError: getCurrent(...).then is not a function 错误
  • 您应该检查您的数据库文档以确保.aggregate 方法返回Promise。从您的错误来看,情况可能并非如此。
猜你喜欢
  • 1970-01-01
  • 2020-04-17
  • 2018-12-21
  • 2017-04-21
  • 2019-08-19
  • 2016-10-23
  • 2014-09-07
  • 2015-09-08
相关资源
最近更新 更多