Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda