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
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
}
};