Node js 、 mongo DB 使用异步从多个集合中获取数据
您好,我正在尝试从数据库获取我所有的博客并更改作者 来自数据库中另一个集合的名称,然后将它们渲染到 ejs 文件,但是页面在数组填满之前呈现
app.get('/', async (req, res) => {
let blogList = new Array();
await Blog.find({}, function (err, foundBlog) {
console.log(foundBlog);
if (err) {
console.log(err);
} else {
foundBlog.forEach(async (blog) => {
await Author.findById(blog.author, async (err, author) => {
if (err) {
console.log(err);
} else {
blog.author = author.name;
console.log('this is the blogs' + blog);
blogList.push(blog);
console.log('array length 1 is ' + blogList.length);
}
});
});
console.log('array length 2 is ' + blogList.length);
console.log(blogList);
res.render('home', { blogs: blogList });
}
});
});
Hello im trying to get all my blogs from DB and change the author
name from another collection from the database then rendering them to
ejs file however the page renders before the array is filled up
app.get('/', async (req, res) => {
let blogList = new Array();
await Blog.find({}, function (err, foundBlog) {
console.log(foundBlog);
if (err) {
console.log(err);
} else {
foundBlog.forEach(async (blog) => {
await Author.findById(blog.author, async (err, author) => {
if (err) {
console.log(err);
} else {
blog.author = author.name;
console.log('this is the blogs' + blog);
blogList.push(blog);
console.log('array length 1 is ' + blogList.length);
}
});
});
console.log('array length 2 is ' + blogList.length);
console.log(blogList);
res.render('home', { blogs: blogList });
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请使用博客中作者的引用。换句话说,建立博客与作者的关系。然后您的后端应如下所示:
现在使用此代码,您的整个作者对象将嵌入到每个博客中,如下所示:
您可以通过访问 blog.author.name 轻松获取作者详细信息。
Please use ref of Author in Blog. In other words make a relation of blog with author. And then your backend should be as follows:
With this code now your whole author object will be embedded in each blog like:
And you can easily get author details by accessing blog.author.name.
对于您的查询,您可以在集合中的 Mongo Schema 中探索 populate。
for your query, you can explore populate in your Mongo Schema in the collection.