猫鼬:填充中的选择属性不起作用

时间:2020-02-06 11:51:07

标签: express mongoose

我试图取消选择“ tours”对象中的owner属性,该对象实际上已填充在用户模式中。但是由于我实际上在巡回模式中填充了所有者,所以它不起作用。我尝试了各种方法,但是没有用。

1)用户模型

let userSchema = new mongoose.Schema({
    name: {
        type: String,
        unique: true,
        required: true,
        maxlength: 15,
        minlength: 5
    }, 
    password: {
        type: String,
        required: true,
        minlength: 5
    }
})

userSchema.set('toObject', { virtuals: true })
userSchema.set('toJSON', { virtuals: true })

userSchema.virtual('tours', {
    ref: 'Tour',
    localField: '_id',
    foreignField: 'owner'
})

2)旅游模式

let tourSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
})

tourSchema.pre(/^find/, function(next) {
    this.populate({
        path: 'owner',
        select: 'name'
    })
    next()
})

3)用户控制器

exports.getUser = catchAsync(async (req, res, next) => {
    let user = await User.findById(req.params.id).populate({path: 'tours', select: {'owner': 0}})
    res.status(200).json({
        status: 'success',
        total: user.length,
        user
    })
})

response in postman, I need the owner field gone when populating tours

0 个答案:

没有答案