Last active
August 29, 2015 14:04
-
-
Save artcommacode/cfd5dc6fe872341c06a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var AlbumSchema = new Schema({ | |
| parent: { | |
| type: Schema.Types.ObjectId, | |
| ref: 'Album' | |
| }, | |
| children: [{ | |
| type: Schema.Types.ObjectId, | |
| ref: 'Album' | |
| }], | |
| createdAt: { | |
| type: Date, | |
| }, | |
| updatedAt: { | |
| type: Date, | |
| } | |
| }); | |
| AlbumSchema.pre('save', function (next) { | |
| var now = Date.now() | |
| , album = this | |
| , Album = mongoose.model('Album'); | |
| // only set createdAt if it's a new object | |
| if (album.isNew) album.createdAt = now; | |
| // always set updatedAt each time we touch it | |
| album.updatedAt = now; | |
| // here comes the tricky bit | |
| async.series([ | |
| function (callback) { | |
| // just grab every album | |
| // and remove this one from their 'children' array | |
| Album.update({}, { | |
| $pull: {children: album} | |
| }, {multi: true}, callback); | |
| }, | |
| function (callback) { | |
| // grab the album that we have set as this ones parent | |
| // and stick this album into *that* albums children | |
| Album.update({_id: album.parent}, { | |
| $push: {children: album} | |
| }, callback); | |
| } | |
| ], next); | |
| }); | |
| AlbumSchema.pre('remove', function (next) { | |
| var album = this | |
| , Album = mongoose.model('Album'); | |
| async.parallel([ | |
| function (callback) { | |
| // grab the album that has this one as a child | |
| // and remove this album from its children | |
| Album.update({children: album}, { | |
| $pull: {children: album} | |
| }, callback); | |
| }, | |
| function (callback) { | |
| // grab the album(s) that have this one as its parent | |
| // and remove it as parent | |
| Album.update({parent: album}, { | |
| parent: null | |
| }, {multi: true}, callback); | |
| } | |
| ], next); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment