-1
 const payment = await paymentsSchema.findOne({ student: s_id, guardian: g_id }, {},
          { sort: { 'createdAt': -1 } })
        console.log(payment)
        payment.balance = (payment.balance + settings.overtime_rate)
       
        // Create a new document with the updated values
        const updatedPayment =  paymentsSchema(payment.toObject());

        // Save the new document to the database
        updatedPayment.save((err) => {
          if (err) throw err;
          console.log('Payment updated successfully');
        });

I expect to have 2 documents after posting this update, the original and the updated document...

Wahlstrommm
  • 684
  • 2
  • 7
  • 21
zippy
  • 1
  • 1
  • I get this error when i run the above code: "MongoServerError: E11000 duplicate key error collection:" – zippy May 01 '23 at 12:04
  • Use `findOneAndUpdate`, with `upsert: true` to do it all in one simple query, or just `update` – nimrod serok May 01 '23 at 12:04
  • Hello _nimrod serok, i want to update only after I find the document...i want to do something else if I don't find the document. – zippy May 10 '23 at 20:31

1 Answers1

0
const payment = await paymentsSchema.findOne({ student: s_id, guardian: g_id }, {},
      { sort: { 'createdAt': -1 } },)
    console.log(payment)
    payment.balance = (payment.balance + settings.overtime_rate)
 
    // Create a new document with the updated values
    const updatedPayment = new paymentsSchema({
      balance: payment.balance,
     . . . //other fields you may have
    });

    // Save the new document to the database
    updatedPayment.save((err) => {
      if (err) throw err;
      console.log('Payment updated successfully');
    });
zippy
  • 1
  • 1