When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response.
app.post('/api/persons', (req, res) => {
const data = req.body;
if (!data.name || !data.number) {
return res.status(400).json({
error: 'Name or Number missing',
});
}
const newName = data.name;
Person.find({ name: newName }).then((result) => {
if (result.length !== 0) {
return res.status(409).json({
error: 'Name must be unique',
});
}
});
const record = new Person({
name: data.name,
number: data.number,
});
record.save().then((savedRecord) => {
res.json(savedRecord);
});
});
Person represents a model in mongoDB
The Person.find
method checks the value and returns a boolean. Currently, there are two issues that I need assistance with:
Even after returning a value in the function following the
.find
call, the process continues and the value gets saved using therecord.save()
below.Despite the value being non-existent, the error message
Name must be unique
is displayed. // Solved it by replacing.exist()
with.find()
Is there a way to resolve this without placing the record.save()
inside the find promise? I prefer having the .find
call within its own function. How can I achieve this?
Thank you