Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose error on promise with save?

When i try to get promise back with save operation on instance of model. i get error: undefined is not a function

instance.save().exec().then(..)

However, if i try to get promise with model like this, then it works.

model.find(..).exec().then(..)

Is there no way to get promise for save action. Currently i just pass callback to save function. However, for the sake of consistency i'd like to do all db operations in the same manner.

like image 662
Muhammad Umer Avatar asked Apr 19 '15 23:04

Muhammad Umer


2 Answers

Model#save returns a promise, so you should skip the .exec():

instance.save().then(...);
like image 110
JohnnyHK Avatar answered Sep 29 '22 08:09

JohnnyHK


Something like this?

let mongooseInstance = new MongooseInstance(Obj);
return mongooseInstance
  .save()
  .then(savedObj => {
    if (savedObj) {
      savedObj.someProperty = null;
      success.data = savedObj;
      return Promise.resolve(success);
    } else {
      return Promise.reject(error);
    }
  });

and maybe with a catch?

mongooseInstance
  .save()
  .then(saved => console.log("saved", saved))
  .catch(err => console.log("err while saving", err));
like image 31
xameeramir Avatar answered Sep 29 '22 08:09

xameeramir