所以我有以下内容:
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 });
我的情况是这样的:删除照片时,我也想在包含照片的PhotoAlbum中删除它。我会写什么样的查询来做到这一点?
答案 0 :(得分:1)
您可以在mongodb中使用$pull
。
示例:
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 } } });