Заполнение мангуста игнорирует методы схемы.toJSON()

#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
        }
    }]
})
 

Схема имеет 2 метода, чтобы никогда не показывать определенные поля, когда пользователь читает либо свою собственную информацию, либо информацию о других пользователях.

 // 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())
})
 

I also populate in a similar way when reading a users post, however the following does not cause the same issue as above. Here password etc are deleted as expected.

 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. другое . Я пробовал переключаться между ними.