Stefano
Stefano

Reputation: 302

How to do mongoose query in post save?

How can I query the company name in the post save of the user schema?

UserSchema.post('save', function (doc) {
   console.warn("POST SAVE", doc);
   console.log(this, "---------------------------------------------");
   this.findOne({_id:doc._id})
      .populate('company')
      .exec(function (err, _user) {
         if(err) return next(err);
         else{
            // console.warn("_USER", _user);
            if(_user.company.name) doc.companyName = _user.company.name;
            Sync.syncUser(doc)
               .then(function (_r) {
                  // console.log(_r,"<-----------------------------------------------------------");
                  if (_r) {
                     console.warn("POST SAVE -> SYNC OK!");
                     next();
                  } else {
                     console.warn("POST SAVE -> SYNC ERR: ", err);
                     return next(err);
                  }
               })
               .fail(function (err) {
                  console.warn("POST SAVE -> SYNC ERR: ", err);
                  return next(err);
               });
         }
   });
});

With this code I have a error:

TypeError: this.findOne is not a function

Upvotes: 1

Views: 1094

Answers (2)

francis
francis

Reputation: 4505

this.constructor.findOne didn't work for me. I use doc.constructor.findOne.

Upvotes: 0

jack blank
jack blank

Reputation: 5195

Try User.findOne() instead of this or use this.constructor.findOne

for the first way you might have to do

var User = mongoose.model('User', UserSchema);

Upvotes: 4

Related Questions