Mongoose错误的承诺与拯救?

时间:2022-07-26 02:35:48

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.

难道就没有办法得到拯救行动的承诺吗?目前我只是将回调传递给save函数。但是,为了保持一致性,我希望以相同的方式执行所有db操作。

2 个解决方案

#1


30  

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

模型#save返回一个承诺,因此您应该跳过.exec():

instance.save().then(...);

#2


3  

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));

#1


30  

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

模型#save返回一个承诺,因此您应该跳过.exec():

instance.save().then(...);

#2


3  

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));