如何填充猫鼬对象数组?

时间:2020-07-22 17:18:23

标签: node.js mongodb express mongoose

router.get('/posts', async (req, res) => {
    try {
        const posts = await Post.find({})
        var postsWithOwners = []
        posts.forEach((post) => {
            post.populate('owner').execPopulate().then((post) => {
                postsWithOwners.push(post)
            })
        })
        console.log(postsWithOwners)
        res.render('posts', { posts: postsWithOwners })
    } catch (e) {
        console.log(e)
    }

})

我正在尝试获取一系列帖子,每个帖子都有自己的完整所有者对象,因此我可以像这样进一步在模板中使用它们,而不仅仅是获得其ID。但是,当我运行当前代码时,控制台中会出现一个空数组。

{{#each posts}}
    <p>{{this.description}}</p>
    <p>{{this.owner.username}}</p>
{{/each}}

如何生成具有这些类型的对象和完整所有者子对象的数组?

{
    _id: 5 f186784691422f0c9b7b8a3,
    image: Binary {
        _bsontype: 'Binary',
        sub_type: 0,
        position: 1109727,
        buffer: < Buffer 89 50 4 e 47 0 d 0 a 1 a 0 a 00 00 00 0 d 49 48 44 52 00 00 06 f4 00 00 05 24 08 06 00 00 00 04 9 c f2 35 00 00 0 c 4 b 69 43 43 50 49 43 43 20 50 72 6 f 66 69...1109677 more bytes >
    },
    description: 'lorem ipsum dolor',
    owner: {
        _id: 5 f17228489d7e01c2716f123,
        username: 'mark',
        email: 'mark@gmail.com',
        password: '$2b$08$oYwBpAwt8JcoWCXumzvbWeH7xeoWGdOOJMahG/YuiZxKeAM/dRe.O',
        __v: 0
    },
    __v: 0
}

我的帖子架构

const postSchema = new mongoose.Schema({
    description: {
        type: String,
        required: false
    },
    image: {
        type: Buffer
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
})

1 个答案:

答案 0 :(得分:0)

为什么?

由于这部​​分代码,您得到一个空数组

post.populate('owner').execPopulate()

是异步的,并且.forEach循环在继续进行下一个循环迭代之前不会等待它完成。当forEach循环完成时,.execPopulate方法调用将无法解决,因此,postsWithOwners的日志将输出一个空数组,因为没有任何内容被推入其中。

修复:

您可以找到一种方法来等待循环中的每个execPopulate调用,但您可以直接在.populate查询上添加一个find,而不必这样做,知道如何填充要返回的每个Post文档的所有者子文档。像这样:

router.get('/posts', async (req, res) => {
    try {
        const posts = await Post.find({}).populate('owner')
        // The Post documents returned should have their owner subdocument populated
        console.log(posts);
        res.render('posts', { posts })
    } catch (e) {
        console.log(e)
    }
})

有用链接

  • 您可以在javascript循环here
  • 中了解有关异步操作的更多信息