I getting errors when using model.find in mongoose for using a callback function which is not allowed in the newer versions.
here is the code as I wrote it with callback functions
app.post("/api/users", (req, res) => {
exerciseData.findOne({username: req.body.username}, function (err, data) {
if (err) return console.log(err);
if (!data) {
const createNewRecord = (done) => {
let newRecord = new exerciseData({username: req.body.username});
newRecord.save(function(err, data) {
if (err) return console.error(err);
console.log("Document inserted succussfully :" + data);
res.json({
username: data.username,
_id: data._id
});
done(null, data)
});
};
createNewRecord((err, data) => {
if (err) return console.error(err);
});
}
else {
res.json({
username: data.username,
_id: data._id
});
}
console.log(data)
});
});
I have tried to use the following code but when my if statement condition (!data) is met it doesn’t
the console log not found is not outputted to the console so it seems that i am missing something. Also my console log for data shows the whole record but if i use dot notation data.username it shows up as undefined.
app.post("/api/users", async (req, res) => {
try {
const data = await exerciseData.find({username: req.body.username});
if (!data) {
console.log("not found")
}
else {
res.json({
username: data.username,
_id: data._id
});
console.log(data);
}
}
catch (err) {
console.log(err);
}
});
also here is a link to my replit
https://replit.com/@CraigMarc/boilerplate-project-exercisetracker#index.js