Nodejs mongoose findOne 怎么合并多个结果
Nodejs mongoose findOne 怎么合并多个结果
Article.findById(aid, function (err, adoc){ adoc.user = User.findOne(adoc._id,function (err, udoc){ return udoc; }); return adoc; });
返回的是JQ对象和json的混合 怎么解决
5 回复
在使用 Mongoose 的 findOne
方法时,如果需要合并多个查询的结果,通常需要处理异步操作。上述代码中,User.findOne
是一个异步操作,而直接在回调函数中返回结果会导致逻辑上的混乱。为了解决这个问题,我们可以使用 async/await
或者 Promise 来更好地管理这些异步操作。
以下是一个改进后的示例代码,展示了如何使用 async/await
来合并多个查询的结果:
const mongoose = require('mongoose');
const Article = mongoose.model('Article', new mongoose.Schema({}));
const User = mongoose.model('User', new mongoose.Schema({}));
// 定义一个异步函数来获取文章和用户信息
async function getArticleAndUser(aid) {
try {
// 查找文章
const adoc = await Article.findById(aid).exec();
if (!adoc) {
throw new Error("Article not found");
}
// 查找用户
const udoc = await User.findOne({_id: adoc.userId}).exec();
if (!udoc) {
throw new Error("User not found");
}
// 合并结果
adoc.user = udoc;
return adoc;
} catch (error) {
console.error(error);
return null;
}
}
// 使用该函数
getArticleAndUser(someAid)
.then(result => {
if (result) {
console.log(result);
} else {
console.log("Failed to fetch article or user.");
}
})
.catch(err => {
console.error("An error occurred:", err);
});
解释
- 定义模型:首先确保你已经定义了
Article
和User
模型。 - 异步函数:创建一个名为
getArticleAndUser
的异步函数,用于查找文章和用户信息。 - 查找文章:使用
await
关键字等待Article.findById(aid)
查询完成。 - 查找用户:在找到文章后,使用
await
等待User.findOne
查询完成。 - 合并结果:将查找到的用户信息合并到文章对象中。
- 错误处理:通过
try/catch
块来捕获并处理可能发生的错误。
这样,你就可以正确地合并多个查询的结果,并且避免了原始代码中的异步问题。
3级怎么办 Corpus => Article => User
Mongoose 本身可以 promise,那就可以这样写了:
var result;
Corpus.findById(corpusid)
.populate('article')
.exec()
.then(function(corpus) {
result = corpus;
return corpus.article.populate('user').exec();
})
.then(function(article) {
result.article = article; // user已经 populate 出来了 :p
});
其实这个不是一个好的解决方法,你可以看 mongoose 的3.6的release notes 它已经支持 populate('parent.child')
这样的写法了。