Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB Schema Array Issue

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

$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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading