【问题标题】:TypeError Bug in Post RoutePost Route 中的 TypeError 错误
【发布时间】:2020-08-15 12:12:51
【问题描述】:

我正在构建一个非常基本的类似 Yelp 的 API。在我的业务 POST 路由中,我可以将业务添加到本地 Mongo 数据库实例,但是,当我在同一路由中进行第二次数据库调用以将新业务文档的 ID 推送到我的用户集合中的“业务”数组中时(在所有者下注册企业)我在负责执行此操作的功能中出现错误,说:'TypeError: "Cannot convert undefined or null to object"' 这是我的代码:

添加业务并尝试注册用户的 API POST 路由

尝试将企业 ID 添加到用户集合的函数(违规代码)

const { getDb, getUserId } = require('../lib/mongo')

//function to add a new business
exports.userAddBusiness = async function (businessId) {
    const db = getDb()
    const collection = db.collection('users')
    try {
        result = await collection.updateOne({
            $push: { "businesses": businessId }
        })
        return "Business " + businessId + " registered under user " + getUserId()
    } catch (error) {
        return "Failed to register business " + businessId + " under user " + getUserId() + "because " + error
    }
}
/*
 * Route to create a new business.
 */
router.post('/', async function (req, res, next) {
  //if request passes validation
  if (validation.validateAgainstSchema(req.body, businessSchema)) {
    try {
      const business = validation.extractValidFields(req.body, businessSchema)
      //insert the business into the db
      let generatedId = await addBusiness(business)
      console.log(generatedId)
      //register business under owner and print result
      let res = await userAddBusiness(generatedId)
      console.log(res)
      res.status(201).json({
        id: generatedId,
        links: {
          business: `/businesses/${generatedId}`
        }
      })
    } catch (err) {
      res.status(400).json({
        error: "Failed to add and register new business" + err
      })
    }
  } else {
    res.status(400).json({
      error: "Request body is not a valid business object"
    })
  }
})

这是我从两个代码块中删除 try/catch 块时的错误堆栈:

 Business 5eab79e21f9878001963a747 has been successfully added.
api             | (node:25) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
api             |     at Function.keys (<anonymous>)
api             |     at checkForAtomicOperators (/usr/src/app/node_modules/mongodb/lib/operations/collection_ops.js:61:23)
api             |     at Collection.updateOne (/usr/src/app/node_modules/mongodb/lib/collection.js:749:15)
api             |     at exports.userAddBusiness (/usr/src/app/models/users.js:8:39)
api             |     at /usr/src/app/api/businesses.js:50:23
api             |     at processTicksAndRejections (internal/process/task_queues.js:86:5)
api             | (node:25) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

【问题讨论】:

  • 为什么不用行号发布错误堆栈
  • @AsifM 我已将错误堆栈添加到我的原始帖子中。请注意,获取此堆栈的唯一方法是从我的原始代码中删除 try/catch 块(因为这些块不会退出程序而是在继续之前捕获错误)

标签: javascript node.js mongodb api asynchronous


【解决方案1】:

似乎我忽略了 updateOne 函数最明显的方面:传入一个文档 ID...希望当有人搜索与此类似的问题时,他们会找到此帖子并快速修复他们的错误。

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2022-01-19
    • 2019-05-31
    • 2019-05-28
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多