Home > Enterprise >  How do I update nested array values in mongoose?
How do I update nested array values in mongoose?

Time:12-27

I am fairly new to nodejs/express and I'm practicing full stack development with devchallenges.io, i'm doing the shoppingify challenge. I'm trying to update the quantity of an item I am targeting inside of the items array. I understand my attempt below was terrible, I'm really struggling to understand the logic to be able to do so.

// @route    PUT api/list/item/quantity/:id
// @desc     Increase or decrease quantity
// @access   Private
router.put('/item/quantity/:id', auth, async (req, res) => {
  const { action } = req.body;
  try {
    let list = await List.findOne({ user: req.user.id });

    const item = list.items.find(
      (item) => item._id.toString() === req.params.id
    );
    list = list.updateOne(
      { 'items._id': req.params.id },
      { $set: { 'items.quantity': item.quantity   1 } }
    );

    await list.save();
    return res.json(list);
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server Error');
  }
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ListSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
  },
  name: {
    type: String,
    default: 'Shopping List',
  },
  items: [
    {
      name: {
        type: String,
        default: '',
      },
      note: {
        type: String,
        default: '',
      },
      image: {
        type: String,
        default: '',
      },
      category: {
        type: String,
        default: '',
      },
      quantity: {
        type: Number,
        default: 1,
      },
    },
  ],
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = List = mongoose.model('list', ListSchema);

CodePudding user response:

Look this is my update-vendor route here I'm updating nested street and city name.

router.put("/update-vendors", async (req, res, next) => {
  const vendor = await Vendor.updateOne(
    {
      "address.street": "Street2",
    },
    {
      $set: {
        "address.$.street": req.body.street,
        "address.$.city": req.body.city,
      },
    }
  );
  res.status(200).json(vendor);
});

You can update particular things with the help of $set and other $push method

  • Related