Home > Mobile >  mongoDB deletes array after put operation
mongoDB deletes array after put operation

Time:10-19

I have a controller:

exports.chooseTransporter = (req, res, next) => {
  const transporter = new Signup({
    _id: req.params.signupId,
    approved: req.body.approved
  });
  Signup.updateOne({ _id: req.params.signupId}, transporter).then(result => {
    res.status(201).json({
      message: "Signup updated!",
      result: result
    });
  })
  .catch(err => {
    res.status(500).json({
      message: "DB error!"
    });
  });
}

and model:

const mongoose = require("mongoose");

const signupSchema = mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
  cargoId: { type: mongoose.Schema.Types.ObjectId, ref: "Cargo", required: true },
  truckIds: [{type: mongoose.Schema.Types.ObjectId, ref: "Truck", required: true }],
  approved: { type: Boolean ,required: true },
  finished: { type: Boolean ,required: true }
});

module.exports = mongoose.model("Signup", signupSchema);

After creating a signup my collection looks like below:

{
    "_id" : ObjectId("616eb5061aeeabc39184696d"),
    "truckIds" : [ 
        ObjectId("6131f12e8ed8b949f6752c59"), 
        ObjectId("6137150e1b92ae2bf762f87b")
    ],
    "userId" : ObjectId("60868c31caafe530e7e2d04a"),
    "cargoId" : ObjectId("614da0b0812a2f6169163d37"),
    "approved" : false,
    "finished" : false,
    "__v" : 0
}

After running a chooseTransporter method and setting approved to true, my truckIds array is 0 elements like below:

{
    "_id" : ObjectId("616eb5061aeeabc39184696d"),
    "truckIds" : [],
    "userId" : ObjectId("60868c31caafe530e7e2d04a"),
    "cargoId" : ObjectId("614da0b0812a2f6169163d37"),
    "approved" : true,
    "finished" : false,
    "__v" : 0
}

Thanks in advance!

CodePudding user response:

Try to change the updateOne parameters and specify only the approved attribute:

Signup.updateOne({ _id: req.params.signupId }, { approved: req.body.approved })
  .then((result) => {
    res.status(201).json({
      message: 'Signup updated!',
      result: result,
    });
  })
  .catch((err) => {
    res.status(500).json({
      message: 'DB error!',
    });
  });

  • Related