Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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
  }
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!