Updating embeded document in MongoDB/Mongoose

Refresh

March 2019

Views

4 time

0

currently I've this schemas/models:

const carrier = new Schema({
  quantity: Number,
  user: {
    type: ObjectId,
    ref: 'User'
  }
});

const itemsSchema = new Schema({
  name: {
    type: String
  },
  quantity: {
    type: Number,
    min: 0,
    default: 1
  },
  status: {
    type: String
  },
  carriers: [carrier],
  event: {
    type: ObjectId,
    ref: 'Event'
  }
});

If it's a new user I want to push it to the carriers array, I managed that with this code:

Items.findOneAndUpdate({ name }, { $push: { carriers: newCarrier } }, { new: true });

But if the carrier already exists I'm having a hard time to find out how to update the quantity.

My code right now is:

eventData.items.update({ 'carriers': { $elemMatch: { 'user': user._id } } }, { $set: { 'carriers.$.quantity': finalQuantity } });

If someone could help me with that I would be thankful!

0 answers