Home > Blockchain >  How to update a specific object in a array of objects by Item ID in Node.js and Mongoose
How to update a specific object in a array of objects by Item ID in Node.js and Mongoose

Time:01-27

I need a code in Express.Js and Mongodb where I can change an exact string inside an object through the id of the item, I need to change the string "colorSelected" to a new value, changing only what I put in the body, in my previous failed attempts every change I made would change the entire object, I don't want that, thank you in advance.

Router Cart.js
//update color cart
router.patch("/cart/:id", Auth, async (req, res) => {

  

});
Model Cart.js

const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId

const cartSchema = new mongoose.Schema({
    owner : {
        type: ObjectID,
        required: true,
        ref: 'User'
    },
    items: [{
        itemId: {
            type: ObjectID,
            ref: 'Item',
            required: true
        },
        img: String,
        name: String,
        colorSelected: String,
        colors: Array,
        stock: Number,
        quantity: {
            type: Number,
            required: true,
            min: 1,
            default: 1
        },
        price: Number
    }],
    bill: {
        type: Number,
        required: true,
        default: 0
    }
}, {
    timestamps: true
})

const Cart = mongoose.model('Cart', cartSchema)

module.exports = Cart
Model Item.js

const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId

const reviewSchema = mongoose.Schema(
    {
      name: { type: String, required: true },
      rating: { type: Number, required: true },
      comment: { type: String, required: true },
      user: {
        type: ObjectID,
        required: true,
        ref: 'User'
      },
    },
    {
      timestamps: true,
    }
  )

const itemSchema = new mongoose.Schema({
    images: [{
        name: {
            type: String,
            required: true
        },
        src: {
            type: String,
            required: true
        },
        color: {
            type: String,
            required: true
        },
    }],
    owner : {
        type: ObjectID,
        required: true,
        ref: 'User'
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    description: {
        type: String,
        required: true
    },
    category: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    stock: {
        type: Number,
        required: true
    },
    visibility: {
        type: Boolean,
        required: true
    },
    reviews: [reviewSchema],
    rating: {
       type: Number,
       required: true,
       default: 0,
    },
    numReviews: {
       type: Number,
       required: true,
       default: 0,
    }
}, {
    timestamps: true
})

const Item = mongoose.model('Item', itemSchema)

module.exports = Item

Mongo DB

CodePudding user response:

You can use the $set operator in MongoDB's update method to update a specific field in an object within an array. In your Express.js route, you would first find the cart by its ID and then use the updateOne() method to update the colorSelected field in the items array. Here's an example of what the route might look like:

router.patch("/cart/:id", Auth, async (req, res) => {
  try {
    const cart = await Cart.findById(req.params.id);
    const itemId = req.body.itemId;
    const colorSelected = req.body.colorSelected;

    await Cart.updateOne(
      { _id: req.params.id, "items.itemId": itemId },
      { $set: { "items.$.colorSelected": colorSelected } }
    );
    res.status(200).send("Color updated successfully");
  } catch (err) {
    res.status(400).send(err);
  }
});

In this example, req.params.id is used to find the cart by its ID, req.body.itemId is used to find the specific item in the items array, and req.body.colorSelected is used to set the

  • Related