gpt4 book ai didi

node.js - express + Mongoose : async/await returning undefined

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:37 26 4
gpt4 key购买 nike

我试图将路由代码与数据库代码分开,但当路由调用 Controller 方法时,我遇到了错误。

我有productRoutes.js:

router.route('/')
.get(async (req, res, next) => {
try {
let criteria = {};
for (const el in req.query) {
criteria[el] = req.query[el];
}
console.log('Getting all products', criteria);

const result = await controller.getAll(criteria);
console.log('router result:', result);
const status = (result.ok ? (result.count > 0 ? 200 : 404 ) : 400);
return res.status(status).send(result);
} catch (err) {
return next(err);
}
});

productController.js:

exports.getAll = (criteria) => {
model.find(criteria, '-__v').exec((err, records) => {
const ok = (err ? false : true);

let result = {}
result.ok = ok;
if (ok) {
result.data = records;
result.count = records.length;
} else {
result.count = 0;
result.err = err;
}

console.log('controller result count:', result.count);

return result;
});
}

执行时会产生以下结果:

Getting all products {}
router result: undefined
TypeError: Cannot read property 'ok' of undefined
at router.route.post.get (C:\dev\projects\mercante\server\routes\productRoutes.js:58:36)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
controller result count: 4

执行不会等待 controller.getAll(criteria)

我尝试过一些寻找类似问题的代码,例如 try/catch 异步调用,但没有成功或者我错过了一些细节。

提前致谢。

最佳答案

原因:您的 Controller 的 getAll 方法没有返回任何值。

你应该这样做:

exports.getAll = async (criteria) => {
// Return value!
return await model.find(criteria, '-__v');
}

关于node.js - express + Mongoose : async/await returning undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com