外国 collection 似乎没有出现在汇总数据中

Foreign collection doesn't seem to be appearing in aggregated data

我正在制作一个简单的论坛,想要 link 两个 collection,这样我就可以显示有关在 post 上创建 post 的用户的数据:

User.js:

_id:60ccb13a21d65f0c7c4c0690
username: testuser
name: test

和Createpost.js

_id:60d80b1305dcc535c4bf111a
postTitle: "test post"
postText: "aaaaa"
postUsername: "testuser"

有人建议我尝试 $lookup,所以我有这个:

router.get('/forum', async (req,res)=>res.render('forum', {
    newPost: await Createpost.aggregate([
{
    $lookup: {
         from: "User", 
         localField: "postUsername", 
         foreignField: "username", 
         as: "postUser"
    }
},
{
    $sort: {date: -1}
}  
])}));

然后我在ejs中这样显示:

<% newPost.forEach(newPost => { %>
    Posted by: <%= newPost.postUsername %> - Name: <%= newPost.postUser.name %>
    <%= newPost.postText %>
<% }%>

来自 Createpost.js 的所有数据都工作正常,正在显示 post 用户名和 post 文本,但是当涉及到我尝试加入的数据时,比如姓名,它没有显示任何内容。我尝试在控制台记录聚合数据,看起来 postUser 只是一个空数组,所以我怀疑它没有从“User”获取任何数据?但是我不知道我能做什么,mongodb 中的 collection 被称为 users 而不是 User 但把它放在字符串中也不起作用。

您正在将 'User' 写成 collection 姓名,请检查 collection 中保存的姓名 MongoDB。它应该保存为 'users' collection。所以,你必须像下面的代码一样在查找中写 'users':

router.get('/forum', async (req,res)=>res.render('forum', {
        newPost: await Createpost.aggregate([
    {
        $lookup: {
             from: "users", 
             localField: "postUsername", 
             foreignField: "username", 
             as: "postUser"
        }
    },
    {
        $sort: {date: -1}
    }  
    ])}));