1

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);

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

You're a lifesaver, thanks :)
Great, I glad to see this work for you need more help just let me know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.