Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda