Mongoose 查询深度填充字段

时间:2021-07-29 02:46:38

标签: node.js mongodb mongoose

我有一个名为 topic schema 的模型 schema,其中包含一个名为 parent 的字段,这是对同一实体“topic”的引用,这在某些情况下会生成多个级别的亲属关系,因此我需要进行查询从包含在特定主题的父 ID 中的父 ID 读取。我知道这听起来可能很复杂,但它就像使用过滤器“parent.parent”的请求一样简单。这是我想做的模型和请求,但没有得到我期望的结果:

const topicSchema = new Schema
(
    {
        name: 
        {
            type:String,
            unique:true
        },
        description: 
        {
            type:String
        },
        parent: 
        {
            type: Schema.ObjectId,
            ref:'Topic'
        }
    }
)

async function getAllTopicChildren(topic)
{

        const topicChildren = await Topic.find( {
        $or:
        [
            {parent:topic},
            {'parent.parent':topic},
            {'parent.parent.parent':topic},
            {'parent.parent.parent.parent':topic},
        ]
    }).populate({path:'parent',populate:{path:'parent'}})
        try 
        {
            if(!topicChildren)
            {
                throw new Error('there are no topics')
            }
            else
            {
                return topicChildren
            }
        } 
        catch (error) 
        {
            throw new Error(error.message)
        }
    
}

0 个答案:

没有答案