Home > Software engineering >  Mongoose - express server update specific index in array of objects
Mongoose - express server update specific index in array of objects

Time:01-10

I've created a custom identifier ID and I'm trying to update my coins and aswell as the first array object purchased bool to true.

this is how my data looks like

[
    {
    
        "identifier": "123456789",
        "coins": 100,
        "equipments": [
            {
                "item": "itemname",
                "price": 100,
                "gold": 10,
                "level": 1,
                "condition": 100,
                "purchased": false
            },
            {
                "item": "itemname2",
                "price": 80,
                "gold": 8,
                "level": 1,
                "condition": 100,
                "purchased": false
            },
        ],
        "__v": 0
    }
]

This is my update routes

router.put("/update/:identifier", function(req,res){
  User.find({identifier: req.params.identifier}, function(err, equipment) {
    equipment.coins= 50;
    equipment[0].equipments.purchased = true;
  
    equipment[0].save(function (err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(equipment);
      }
    });
  });
 });

When I run it nothing happens and it doesn't give any errors

CodePudding user response:

This is not the conventional approach. You need to do it like this.

router.put("/update/:identifier", function(req,res){
  User.findOne({identifier: req.params.identifier}, function(err, equipment) {
    equipment.coins= 50;
    equipment.equipments.purchased = true;
  
    equipment.save(function (err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(equipment);
      }
    });
  });
 });

BONUS:I would suggest you to use findAndUpdateOne()

  • Related