本文介绍了如何重命名路径以响应填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的查询:

galleryModel.find({_id: galleryId})
            .populate({
                model: 'User',
                path: 'objectId',
                select: 'firstName lastName'
            })

objectId 的结束响应如下:

objectId: {
...
}

如何在不改变真实路径的情况下将其更改为 user 作为响应?

How can I change it to user in response without changing real path?

推荐答案

您可以通过虚拟填充来实现,在 mongoose 4.5 版中引入.为此,您需要在 mongoose 模式中定义一个虚拟字段.

You can do this by virtual populate, introduced in mongoose version 4.5 . For that you need to define a virtual field in mongoose schema.

var GallerySchema = new mongoose.Schema({
    name: String,
    objectId: {
        type: mongoose.Schema.Types.ObjectId
    },
});

GallerySchema.virtual('user', {
    ref: 'User',
    localField: 'objectId', 
    foreignField: '_id' 
});

Ans 当您运行 find 查询时,只需用用户填充它.

Ans when you run find query, just populate it with user.

Gallry.find({_id: galleryId}).populate('user','firstName lastName').exec(function(error, gallery) {
    console.log(error);
    console.log(gallery);;
});

以上代码未在程序中测试,可能有错别字,您可以在下面的链接中获得有关猫鼬虚拟填充的更多详细信息

Above code is not tested in program, there may be typos, You can get more details about mongoose virtual populate on below link

http://mongoosejs.com/docs/populate.html

这篇关于如何重命名路径以响应填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:30