Monday, 24 April 2017

Mongoose model is empty object inside another model pre save hook

This is inside a Group model, in Group models save prehook its refex is updated for user searching. But mongoose returns "User.find is not a function" and when I console.logged User it returned an empty Object ({}). Why can't I query User inside Group save prehook?

var User = require('./User')
...
    _schema.pre('save', function (next) {
        this.regex = ''
        if (!this.users) { return next() }
        var userIds = this.users.map(s => s._id)
        User.find({ _id: { $in: userIds } }).select('name surname').lean().then(docs => {
            docs.forEach(d => {
                this.regex += (' ' + d.name + ' ' + d.surname)
            })
            next()
        })
    })



via MattJ

No comments:

Post a Comment