Node-js,mongo-DB使用async从多个集合中获取数据



你好,我正在尝试从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 });
}
});
});

请在博客中使用作者的ref。也就是说,建立博客与作者的关系。然后你的后端应该如下:

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 
}
});

有了这段代码,你的整个作者对象将嵌入到每个博客中,比如:

blog={
name:"",
author:{
name:"Abc",
}
}

您可以通过访问blog.author.name.轻松获取作者详细信息

对于您的查询,您可以在集合中的Mongo Schema中探索填充。

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)
}
)

最新更新