0

When I update balance, I need to keep paymentCost and Date information as a Array. But I see only one payments info in everytime.

This is my user Model:

const userSchema = new Schema({
    username:{
        type: String,
        require: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String,
        require: true,
    },
    balance: {
        type: Number,
        require: false,
    },
    payments: [{paymentCost: Number, paymentDate: Date}],
    date: {
        type: Date,
        default: Date.now()

    }
})

and this is my update function:

User.findOneAndUpdate(
    { _id: user._id }, 
            { $set: { "balance" : currentBalance, "payments":{"paymentDate": productCost, "paymentDate":date}}},

   async function (error, success) {
         if (error) {
            return callback({
                message: "Balance not updated"
            })
         } else {
            user = await User.findOne({email});
            return callback(null, {...user.toJSON()})
             console.log(success);
         }
     });

And I see every time below output:

enter image description here

Only one payments information keeps in time, how can I keep all of them in Array?

0

2 Answers 2

1

$set is going to replace your current value instated of use $set you can try $push it will push your last object last on array and also if your want your last pushed object shoud be on first your can use the $pop

Sign up to request clarification or add additional context in comments.

3 Comments

When I replace set with push I get this error: message: "Balance not updated". I used like this { $push: { "balance" : currentBalance, "payments":{"paymentDate": productCost, "paymentDate":date}}},
You can have to set your update query like that your find query their { $set: { your value }, $push: { your pushed object their } }
It works now thank you. I changed as your suggestion { $set: { "balance" : currentBalance}, $push: { "payments" : {"paymentDate": productCost, "paymentDate":date}}},
0

With @Naim Biswas's help, my problem solved with below functions:

User.findOneAndUpdate(
    { _id: user._id }, 
    { $set: { "balance" : currentBalance},
    $push: { "payments" :  {"paymentCost": productCost, "paymentDate":date}}},
   async function (error, success) {
         if (error) {
            return callback({
                message: "Balance not updated"
            })
         } else {
            user = await User.findOne({email});
            return callback(null, {...user.toJSON()})
             console.log(success);
         }
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.