0

This is my spa schema.

const spaSchema = new Schema({
  name: String,
  contactNumbers: String,
  address: String,
  images: [String],
});

I want to delete the element in the images array where the element name is 'abc.jpg' and documant id is x. How do I achive this?

2 Answers 2

2

I not really sure about your question, so I will cover 2 options. On both, I will assume that you are making an update on the spa collection.

1) Removing the images field from the document

To totally remove the field images from the desired document you can use the MongoDB $unset operator, as:

Original document:

{
  _id : ObjectId('some_id'),
  name : 'abc.jpg',
  contactNumbers: '...',
  address: '...',
  images: ['...']
}

Update method:

Spa.update(
 { name : 'abc.jpg', _id : ObjectId('some_id') },
 { $unset : { images : null } }
);

That will result in the :

{
  _id : ObjectId('some_id'),
  name : 'abc.jpg',
  contactNumbers: '...',
  address: '...'
}

2) Removing one element within the images field

If you are trying to remove just one element with a specific value from the images array, you can use the MongoDB $pull operator, like:

Original document:

{
  _id : ObjectId('some_id'),
  name : '...',
  contactNumbers: '...',
  address: '...',
  images: ['123.jpg','abc.jpg','def.jpg']
}

Update method:

Spa.update(
 { _id : ObjectId('some_id') },
 { $pull : { images : 'abc.jpg' } }
);

That will result in the :

{
  _id : ObjectId('some_id'),
  name : '...',
  contactNumbers: '...',
  address: '...',
  images: ['123.jpg','def.jpg']
}

I hope that is what you looking for. =]

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

1 Comment

Thanks a lot. =)
1

To remove one element from images(where you store image's name) you should use $pull as bellow

Spa.update(
 { _id : mongoose.Types.ObjectId('some_id') },
 { $pull : { images : 'IMAGE_NAME_THAT_YOU_WANT_TO_REMOVE_FROM_ARRAY' } }
);

1 Comment

Thanks a lot. =)

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.