jsonDoge
jsonDoge

Reputation: 722

Mongoose model is empty object inside another model pre save hook

This is inside a Group model, in Group models save prehook its regex 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()
        })
    })

Upvotes: 0

Views: 803

Answers (1)

BEJGAM SHIVA PRASAD
BEJGAM SHIVA PRASAD

Reputation: 2241

Just move User defination inside hook will work.

 _schema.pre('save', function (next) {
     var User = require('./User')
        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()
        })
    })

Upvotes: 1

Related Questions