0

I'm trying to Promisify the following function

let Definition = mongoose.model('Definition', mySchema)
let saveDefinition = (newDefinition) => {
  var newDef = new Definition(newDefinition);
  newDef.save();
  return Definition.find();
}

to achieve the following sequence of events

let saveDefinition = (newDefinition) => {
  return = new Promise((res, rej) => {
    // newDef = new Definition(newDefinition)
    // then
    // newDef.save()
    // then
    // return Definition.find()
  })
}

The goal is to invoke this function upon a request from the client, save a document to the model called "Definition" and return all of the documents within the model back to to the client. Any help or guidance would be greatly appreciated.

I'm not really sure on how to approach the problem

  • 3
    Nothing to [promisify](https://stackoverflow.com/q/22519784/1048572) here - mongoose methods already do return promises, so [you should not use `new Promise`](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Mar 25 '22 at 00:53
  • Thanks for the feedback, I'll stick with the original function – pschaefferkoetter Mar 25 '22 at 23:57
  • @Aditya That's not how promisification works. – Tomalak Mar 29 '22 at 08:13
  • @Tomalak, but I thought async await is a beautified way of writing promise based functions. Isn't it? – Aditya Mar 29 '22 at 08:51
  • 1
    @Aditya Depends on your preferences. But a function that does nothing more than create a promise (e.g. via an API), and return it, gains nothing from an additional `async`/`await`. – Tomalak Mar 29 '22 at 08:53

1 Answers1

0

a function that creates a mongoose model instance (i.e. a document), saves it to the model, and returns then returns the model

There is nothing special you need to do. .save() already returns (a promise for) the saved document. Return it.

const Definition = mongoose.model('Definition', mySchema);

const saveDefinition = (data) => {
  const newDef = new Definition(data);
  return newDef.save();
};

Done.


I would write it differently to get rid of that global Definition variable:

const saveObject = modelName => {
  const Model = mongoose.model(modelName, mySchema);
  return (data) => new Model(data).save();
};

const saveDefinition = saveObject('Definition');
const saveWhatever = saveObject('Whatever');

Usage is the same in both cases

saveDefinition({ /* ... */ }).then(def => {
  // success
}).catch(err => {
  // failure
});

or

async () => {
  try {
    const def = await saveDefinition({ /* ... */ });
    // success
  } catch (err) {
    // failure
  }
};
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Nothing wrong with the global (module-scoped) `Definition`, the model will likely be used in multiple places – Bergi Mar 29 '22 at 10:56
  • @Bergi No, not inherently - my `saveObject()` is in the same spot, after all. But wrapped into a factory like this, it's easier to re-use. – Tomalak Mar 29 '22 at 10:59