猫鼬填充忽略模式 methods.toJSON()

时间:2021-03-17 01:05:59

标签: node.js mongodb mongoose mongoose-schema mongoose-populate

我有一个用户架构,它在填充时“忽略”schema.methods.toJSON() - 仅在某些情况下。架构类似于以下内容:

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        lowercase: true,
        unique: true,
        maxlength: 320
    },
    name: {
        type: String,
        required: true,
        trim: true,
        maxlength: 40
    },

    .... some other fields ...
   
    notifications: [{
        notification: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Notification',
            required: true
        }
    }]
})

当用户阅读自己的信息或其他用户的信息时,Schema 有两种方法永远不会显示某些字段。

// don't return password or tokens etc
userSchema.methods.toJSON = function () {
    const userObject = this.toObject()
    delete userObject.password
    delete userObject.tokens
    delete userObject.admin
    delete userObject.email
    delete userObject.notifications
    delete userObject.liked

    return userObject
}


// when user is reading their *own* profile, allow a few more fields
userSchema.methods.toPrivateJSON = function () {
    const userObject = this.toObject()

    delete userObject.password
    delete userObject.tokens
    delete userObject.admin

    return userObject
}

当我按如下方式填充 notifications.notification.from 时(返回一个用户),我会返回每个字段。

router.get('/user', auth, async (req, res) => {
    await req.user.populate('posts.post').execPopulate()
    await req.user.populate('saved.article').execPopulate() 
    await req.user.populate('notifications.notification').execPopulate()
    await req.user.populate('notifications.notification.from').execPopulate() 
    // ^ returns *all* fields that appear in the schema
    // password, admin status etc

    res.send(req.user.toPrivateJSON())
})

我在阅读用户帖子时也以类似的方式填充,但是以下内容不会导致与上述相同的问题。这里密码等按预期删除。

const article = await Article.findOne({ link })

await article.populate('author').execPopulate()
await article.populate('comments.comment').execPopulate()
await article.populate('comments.comment.user').execPopulate() 
// ^ *only* returns expected fields
// password, admin etc are not shown

if (!article) {            
    return res.status(404).send()     
}
res.send(article)

值得注意的是,填充 notifications.notification.from 会忽略 methods.toJSONmethodstoPrivateJSON.。我试过在两者之间切换。

0 个答案:

没有答案