[英]Node js , mongo DB get data from multiple collections using async
你好,我正在嘗試從數據庫中獲取我所有的博客,並從數據庫中的另一個集合中更改作者姓名,然后將它們呈現為 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 });
}
});
});
請在博客中使用作者的參考。 換句話說,建立博客與作者的關系。 然后你的后端應該如下所示:
app.get('/', async (req, res) => {
const blogs=await Blog.find({}).populate('author').exec(); // field name author is being populated.
res.render('home', { blogs });
}
);
const BlogSchema=new mongoose.Schema({
... rest of fields,
author:{
type:ObjectId,
ref:"Author" // here it is model name
}
});
使用此代碼,您的整個作者 object 將嵌入每個博客中,例如:
blog={
name:"",
author:{
name:"Abc",
}
}
您可以通過訪問 blog.author.name 輕松獲取作者詳細信息。
對於您的查詢,您可以在集合中探索填充到您的 Mongo 架構中。
const BlogSchema = new mongoose.Schema({
author:{
type:ObjectId,
ref:"Author" //here it is model name
}
})
const Blog = mongoose.model("Blog", BlogSchema )
const AutherSchema = new mongoose.Schema({
_id:{
type:ObjectId
}
})
const Auther = mongoose.model("Auther", AutherSchema)
app.get('/', async (req, res) => {
const blogs = await Blog.find({}).populate('author').exec(); // field name author is being populated.
res.send(blogs)
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.