Home > Enterprise >  Can't Update Data in MongoDB using Mongoose
Can't Update Data in MongoDB using Mongoose

Time:02-20

These are my Schemas

 const dataSchema = new mongoose.Schema({
  email:String,
  date:String,
  amount:Number
})
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  data:[{
      type: mongoose.Schema.Types.ObjectId,
      ref: "UserData",
   }],
})

const User = new mongoose.model("User", userSchema);
const UserData = new mongoose.model("UserData", dataSchema);

I wish to update Data whenever a user post it. If the Userdata on the particular date already exists i wish to update it by adding the prev amount and new amount

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("/");
      }

    }
    
  })
 
})

But it seems the data is always zero in database See the amount section

See the amount section it is still zero. Can anyone tell me what am i doing wrong. I have used set method but new data is unable to be posted.

CodePudding user response:

You have to add callback to your update function.

UserData.findOneAndUpdate(
  {email:username,date:Date},
  {$set:{amount:b}},
  function (error, success){}
)

If you don't want to use callback, then you have to use .exec()

UserData.findOneAndUpdate(
  {email:username,date:Date},
  {$set:{amount:b}},
).exec()

CodePudding user response:

did you check the value of amount? Check the amount value in console.

  • Related