0

When I use mongoose functions, such as find, save, updateOne ect..
What is the best practice to return a obj/success/failure?
untill now I returned a new promise, but maybe there is a built in functionallity?

example code I use untill now:

function updatePost(name) {

  return new Promise((resolve, reject) => {
        mongooseModel.updateOne({_id: id}, {title: title,author: author,body: body}, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }   
    });
  });
}

so I thought maybe mongooseModel.updateOne is a promise by itself that can return this error/success without my new promise.

and if not, what is the bast practice to do something like that?

shamgar
  • 120
  • 9

1 Answers1

0

You can do like this.

Ref. https://mongoosejs.com/docs/api/model.html#model_Model.updateOne

async function updatePost(name) {
  try {
    const res = await mongooseModel.updateOne(
      { _id: id },
      { title: title, author: author, body: body }
    );
    return res;
  } catch (err) {
    throw err;
  }
}
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
  • what does ```res``` get? a string? the object? and what about functions that return a result like ```find()``` I have to make a callback right? – shamgar Aug 11 '21 at 13:10
  • @shamgar, related [question](https://stackoverflow.com/a/32811548/14032355) here. – ikhvjs Aug 11 '21 at 13:13