Mongoose - 是否可以在突变中访问模式属性?

Mongoose - Is it possible to access schema properties inside a mutation?

这里是新手。我正在尝试创建一个电影推荐应用程序,并且我已经为这个授权问题苦苦挣扎了一段时间。我的目标是拥有一个带有布尔值 'isAdmin' 属性 的单一用户模式,以区分普通用户和管理员用户。问题是,当我尝试查询突变中的 isAdmin 变量以确保从上下文传入的登录用户具有执行该操作所需的权限时,我得到了未定义。

用户架构

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        index: {
            unique: true
        }
    },
    email: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    password: {
        type: String,
        required: true
    },
    contributions: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Movie'
    },
    isAdmin: {
        type: Boolean,
        required: true,
        default: false
    }
})

新电影突变

newMovie: async (parent, args, { models, user }) => {
        if (!user){
            throw new AuthenticationError('You must be signed in to submit a new movie')
        }
        console.log(user.isAdmin)
        if (user && user.isAdmin === false) {
            throw new ForbiddenError('You are not qualified')
        }
        return await models.Movie.create({
            title: args.title,
            year: args.year,
            addedBy: mongoose.Types.ObjectId(user.id)
        })
    }

我试图通过控制台日志 user.isAdmin 来查看值,但我却变得不确定。我也尝试过将枚举值 'user and admin' 用于 属性 'roles',结果相同。

经过几个小时的努力,我意识到从上下文加载用户 returns 一个只有 ObjectId 和 iat 的对象,我认为这是对象的创建日期。要访问上下文用户的其余属性,我必须在模型中搜索用户并将其分配给一个变量,从中我可以访问其余属性。

    newMovie: async (parent, args, { models, user }) => {
        if(!user){
            throw new AuthenticationError('You must be logged in')
        }
        active = await models.User.findById(user.id)

        if(active && active.role !== "ADMIN"){
            throw new ForbiddenError('Only users can leave reviews')
        }
        return await models.Movie.create({
            title: args.title,
            year: args.year,
            addedBy: mongoose.Types.ObjectId(active.id)
        })

这是这个问题的有效解决方案。