后路由中的TypeError错误



我正在构建一个非常基本的类似Yelp的API。在我的企业POST路由中,我可以将一个企业添加到我的本地Mongo DB实例中,但是,当我在同一路由中进行第二次数据库调用,将新业务文档的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)

我似乎忽略了updateOne函数最明显的方面:传递文档ID……希望当有人搜索类似于此问题时,他们能找到这篇文章并迅速纠正错误。

最新更新