选择和填充 不要一起工作 Mongodb



我正在尝试填充menteeList.userRecord,只选择名称和配置文件。但也要填充配置文件。但是,如果我执行以下操作:

    Profile.findOne({ user: req.user._id }).populate({
            path: 'menteeList.userRecord',
            populate: { path: 'name profile', 
             select:'name profile',
                   populate: { path: 'profile_picture' }, select: 
                     'profile_picture' }
                    })
它只会显示

名称,并且只会显示配置文件 ID "profile": "5c9ae48eedd2dd561c09083c"

如果我这样做:

   Profile.findOne({ user: req.user._id }).populate({path: 'menteeList.userRecord',populate: { path: 'profile_picture' }, 
select: 'profile_picture' }})

然后它将填充所有字段没有问题,但我正在尝试仅选择名称和填充的配置文件(我只是使用此示例来表明路径定义是正确的(

当前获取的配置文件文档中的学员列表定义

menteeList: [
        {
            name: { type: String, required: true },
            avatar: { type: String, required: true },
            userRecord: {
                type: Schema.Types.ObjectId,
                ref: 'User'
            }
        }
    ]

用户架构中的配置文件定义

name: {
        type: String,
        required: true
    },
    profile: {
            type: Schema.Types.ObjectId,
            ref: 'Profile'
        },

从你的第二个查询的参考来看,我认为你的第一个查询是错误的,

试试这个:

Profile
    .findOne({ user: req.user._id })
    .populate({
        path: 'menteeList.userRecord',
        select:'name profile profile_picture',
        populate: { 
            path: 'profile_picture',
            select: 'profile_picture'
        }
    })

这将告诉mongodb填充userRecord,并仅选择nameprofileprofile_picture(因为我们也需要填充profile_picture,所以我们也需要将其包含在select中(。

接下来,我们可以填充profile_picture并从中选择profile_picture

我希望这对你有所帮助。

最新更新