首页 > 解决方案 > Mongoose 无法填充 ObjectId 的数组

问题描述

const { Schema } = require('mongoose');

const ModuleSchema = new Schema({

    contentType: {
        type: String,
        default: 'module',
        required: true
    },
    author: {
        type: String,
        default: 'Admin',
        required: true
    },
    name: {
        type: String,
        required: true
    },


    content: [
         { type: Schema.Types.ObjectId, ref: 'TextBlock' },  <---- only first is rendered
         { type: Schema.Types.ObjectId, ref: 'Question' } <----- is not rendered
    ]
},
    {timestamps: true});

-- in router

router.get('/:id', (req, res, next) => {

    const id = req.params.id

    Module.findById(id)
        .populate('content')
        .then(m => {
            res.status(200).json(m)
        })})

问题是我只渲染了数组内容的第一个元素。在这种情况下是一个 TextBlock。如果我交换 2 个元素,我只会得到渲染问题。

可能我使用了错误的语法,但找不到任何示例..

请帮忙

标签: node.jsmongoosemongoose-schemamongoose-populate

解决方案


推荐阅读