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?
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 } } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.