简体   繁体   中英

Mongoose: Deleting deeply nested array subdocuments

I'm starting my first real project and have been running into frustrations regarding how to deal with nested subdocuments in Mongoose.

What's the best approach for deleting subdocuments that are nested 2 or 3 times, and we don't know the exact index of the array?

eg for a schema that looks like:

var showSchema = new mongoose.Schema({
    title: String,
    description: String,
    seasons: [{
        name: String,
        videos: [{
            description: String,
            url: String,
            comments: [{
                content: String,
                authorName: String,
            }]
        }]
    }]
});

I've seen mention of using something like:

Show.findByIdAndUpdate({'_id': showId, 'seasons._id': seasonId}, {'$pull': {'seasons.$.videos': {'videos._id': videoId}}}, function(err)...

Or something of the like.

What about if we wanted to delete a comment? A comment is nested further down and AFAIK MongoDB only allows one $. In my case, I don't know the index of any of these arrays.

Does Mongoose have a method we can use? I haven't had much look figuring out the Mongoose documentation.

I appreciate any help!


EDIT:
I have been told by someone more knowledgeable than I that deep nesting like this is not recommended. Would it be better for me to limit nesting to one level deep and split things off into their own documents that connect with references?

Do you need this to happen atomically? The operation you provided is an atomic operation, where it finds the document and updates it in one operation.

If you do not need that to happen in an atomic fashion, you can simply request the document, edit it as a javascript object so that the nested subdocument is removed, and then save the edited document back to the store.

As per your edit about the data storing mechanism, it will sort of depend. Will you more often than not need the subdocument in combination with the parent document? If you'll always need the subdocument and this sort of deletion is rare, it can be OK to nest like this in my opinion. If you'll rarely need the subdocument joined and this sort of deletion is common, you'll probably want to normalize it out into it's own collection. How many of the subdocuments will there be? If there's a lot, you may want it separate.

(Guessing based on your data structure names, personally I would recommend having comments be a separate collection in this case)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM