提问人:Jeremy Ragsdale 提问时间:11/10/2023 更新时间:11/10/2023 访问量:29
寻找一些关于将 Mongoose 与 express 一起使用的指导
Looking for some guidance on using Mongoose with express
问:
我需要一些帮助来了解如何将猫鼬与 express 一起使用。我找到了一个教程,它帮助我创建了一个 API,该 API 使用 MVC 类型的模式从 MongoDB 返回记录,但它没有返回到我的路由器,而是将结果写入响应,因为它是一个 API......
下面是高级设置
Form.Model - 包含我的 Form 对象的架构
Form.Controller - 包含用于从数据库返回记录的代码
Form.Router - 这是我的路由器,它将结果返回给响应对象。
这是我正在努力解决的示例路由,我想将其转换为某种东西,而不是写入 res,而是返回结果,然后在我的路由器中使用它们。
// Retrieve all Forms from the database.
exports.findAll = (req, res) => {
const email = req.query.solcon;
var condition = email ? { email: { $regex: new RegExp(email), $options: "i" } } : {};
Form.find(condition)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving Forms."
});
});
};
来自我的路由器的代码(可能不正确) 基本上,我想调用表单路由器,返回表单,然后将它们发送到我的索引ejs页面。
router.get('/',function(req, res, next) {
let formList =forms.findAll(req.oidc.user.email);
res.render('index', { title: 'Express', user: req.oidc.user.email, forms : formList });
});
我远非专家,甚至不擅长使用承诺,异步等待......因此,很难更改此代码以正常工作。
有人可以帮我把这个 find all 函数转换为我可以在 Form.Router 中使用的东西,以将结果发送到索引页。
答:
0赞
jQueeny
11/10/2023
#1
您似乎没有做太多事情来保证自己的方法,因此一种选择可能是将逻辑移动到路由器回调中,如下所示:findAll
router.get('/', async function(req, res, next) { //< Mark callback as async
try{
const email = req.query.solcon;
const condition = email ? { email: { $regex: new RegExp(email), $options: "i" } } : {};
const formList = await Form.find(condition); //< Now you can await the results
res.render('index', {
title: 'Express',
user: req.oidc.user.email,
forms: formList
});
}catch(err){
console.log(err);
res.render('index', {
title: 'Express',
message: 'Error on server'
});
}
});
或者,您可以像这样用作回调:findAll
exports.findAll = async (req, res) => { //< Mark as async
try{
const email = req.query.solcon;
const condition = email ? { email: { $regex: new RegExp(email), $options: "i" } } : {};
const formList = await Form.find(condition); //< Now you can await the results
return res.render('index', {
title: 'Express',
user: req.oidc.user.email,
forms: formList
});
}catch(err){
console.log(err);
return res.render('index', {
title: 'Express',
message: 'Error on server'
});
}
};
然后在你喜欢的中使用它:router
router.get('/', forms.findAll);
评论