问题描述
我有一个用户架构,它在填充时“忽略”schema.methods.toJSON() - 仅在某些情况下。架构类似于以下内容:
const userSchema = new mongoose.Schema({
email: {
type: String,required: true,lowercase: true,unique: true,maxlength: 320
},name: {
type: String,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.toJSON
和 methodstoPrivateJSON.
。我试过在两者之间切换。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)