Home > Net >  MongoDB Schema Array Issue
MongoDB Schema Array Issue

Time:07-19

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?

CodePudding user response:

$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

CodePudding user response:

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);
         }
     });
  • Related