gpt4 book ai didi

node.js - 使用一个 Mongoose 查询的结果进行另一查询

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:52 25 4
gpt4 key购买 nike

我正在 Node 中构建一个应用程序,并将 Mongoose 与 CosmosDB 结合使用。我想显示与登录用户关联的公司拥有的所有地 block 。

我有一个来自 Passport.js 的用户,我使用他的电子邮件来查询数据库以返回他的公司。效果很好。

我遇到麻烦的地方:一旦我有了他的公司,我想运行第二个查询来获取属于它的所有地 block 。这应该返回一个对象数组,但它返回一个空数组。

两个问题:

  1. 如何使当前代码正常工作?
  2. 当前的结构很尴尬——如何让它更优雅?

代码:

   app.get('/plots',
requireAuth,
function(req, res) {
let company;
User.find({ email: req.user.email }).lean().exec(function(err, results) {
if (err) {
console.log(err);
}
if (!results) {
res.send(null);
return;
} else {
company = results[0].company;
};
}).then(
PlotCast.find({ owner: company }).lean().exec(function(err, results) {
if (err) {
console.log('error', err);
res.send(err);
} else if (!results) {
res.send(null);
} else {
console.log('results', results);
res.send(results);
}
})
).catch(function(e) {
console.log('error', e);
});
}
)

最佳答案

有替代解决方案总没有坏处。

我个人讨厌直接使用 Promises 并更喜欢使用 async.js 。在你的情况下async.waterfall()将会很有用,因为您基本上将结果从一个异步任务传递到下一个异步任务。

app.get('/plots', requireAuth, function(req, res) {
async.waterfall([
function getUser(done) {
// use findOne, not find -- as you only want to retrive ONE user; using find is more expensive
User.findOne({ email: req.user.email }).lean().exec(done);
},
function getCasts(user, done) {
PlotCast.find({ owner: user.company }).lean().exec(done);
},
], function (err, casts) {
// if an error occurs during the above tasks ^, it will come down here
if (err) {
console.log(err);
return res.status(400).send(e);
}
// otherwise if all tasks finish, it will come down here
res.json(casts);
});
});

因此,使用 async.js 的好处是,您可以将所有错误集中在一个地方,而不是在多个地方(这也可以,具体取决于您在做什么)。

我认为你最初的问题是你同时使用了回调和 promise 。通常您使用其中之一。

关于node.js - 使用一个 Mongoose 查询的结果进行另一查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421921/

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