I am working on a project and a service I wrote is running, but it does not give the value I want as a response. I want to create coffee. Every coffee has a certain company. Every time I create coffees, I want the company to also create these coffees in its model.
This is my service
exports.createCoffee = async (coffee, companyId) => {
return await CoffeeModel.create(coffee).then((value) => {
return CompanyModel.findByIdAndUpdate(companyId, {
$push: { coffees: value._id },
});
});
};
This is my controller
exports.createCoffee = async (req, res) => {
try {
const newCoffee = await coffeeService.createCoffee(
req.body,
req.body.company._id
);
res.status(201).json(newCoffee);
} catch (error) {
res.status(500).json(error);
}
};
When I create coffee, it returns the company's information as a response. How can I fix this.
CodePudding user response:
If you want to get the newly created coffee, then you need to return it from the inner promise, instead of company update, maybe after updating the company, and then you can construct your response.
Try this:
exports.createCoffee = async (coffee, companyId) => {
return await CoffeeModel.create(coffee).then(async(value) => {
await CompanyModel.findByIdAndUpdate(companyId, {
$push: { coffees: value._id },
});
return value; // or whatever you want to return..
});
};