This is my Logic for inserting new data for an expense tracking App in Node JS.
My Query is the function createNewData() never executes. If a previous UserData Schema on particular date exists then this code can update it with no Problem.
BUT if UserData Schema does not exists the code is not being able to create a new one.
Should I use something other than UserData.findOne, I had already used findOneAndUpdate() and exists() but nothing works. I am new with Mongoose kindly help
app.post("/insert",(req,res)=>{
const username = req.cookies.username;
const Date = now.toLocaleDateString("en-Uk");
const Amount = req.body.value;
function createNewData(){
const userData = new UserData({
email:username,
date:Date,
amount: Amount
});
userData.save((err)=>{
if(err){
console.log(err);
}else{
console.log('newdatasaved');
res.redirect("/")
}
});
User.findOneAndUpdate({email:username},{$push:{data:userData._id}},(err)=>{
if(err){
console.log('cant push');
}else{
console.log('pushed data');
}
});
}
UserData.findOne({email:username,date:Date},(err,found)=>{
if(err){
createNewData();
console.log('cant find on particular date new created');
}else{
if(found){
let a = Number(found.amount);
let b = Number(Amount)+a;
UserData.findOneAndUpdate({email:username,date:Date},{$set:{amount:b}});
console.log('updated in existing');
res.redirect("/");
}
}
})
})
Creating a separate variable
let xyz = User.findOne({..conditions}).exec();
and then using if
, else
statement helped