mkelley33
mkelley33

Reputation: 5601

How to find by and delete an item in a mongoose array

So I have the following:

const Schema = mongoose.Schema;

const PhotoSchema = new Schema({
  filename: { type: String, required: true },
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  isPublic: { type: mongoose.Schema.Types.Boolean, default: false }
}, { timestamps: true });

const PhotoAlbumSchema = new Schema({
  name: { type: String, required: true },
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  photos: { type: mongoose.Schema.Types.Array }
}, { timestamps: true });

My scenario is this: when I delete a Photo, I want to also delete it in the PhotoAlbum that contains it in photos. What sort of query would I write to do this?

Upvotes: 0

Views: 70

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You can use $pull in mongodb to do it.

Example:

let deleted_photo = await Photo.findOneAndDelete(your_condition);
await PhotoAlbum.updateMany({}, { $pull: {photos: deleted_photo } });
// or
await PhotoAlbum.updateMany({}, { $pull: {photos: {"_id" : deleted_photo._id } } });

Upvotes: 1

Related Questions