I think this is a bigger question of relationships in Mongoose and how in the world we're supposed to make them, but I'll give the details anyways.
My mongoose middleware function is throwing errors.
UserSchema = new Schema(
...
websites: [
type: mongoose.Schema.Types.ObjectId
ref: 'Website'
]
cards: [
type: mongoose.Schema.Types.ObjectId
ref: 'Card'
]
)
...
UserSchema.pre 'remove', (next) ->
cards = this.cards
websites = this.websites
async.parallel [
# remove cards
(done) =>
async.each( cards,
(card_id, cardDone) =>
Card.findById card_id, (err, card) =>
console.log "find card", err if err
if err
cardDone err
else
if card
card.remove (err, card) =>
console.log "remove card", err if err
if err
cardDone err
else
cardDone()
else
cardDone new Error("Card not found")
(err) ->
if err
done err
else
done()
)
# remove websites
(done) ->
async.each( websites,
(website_id, websiteDone) ->
Website.findById website_id, (err, website) ->
console.log "find website", err if err
if err
websiteDone err
else
if website
website.remove (err, website) ->
console.log "remove website", err if err
if err
websiteDone err
else
websiteDone()
else
websiteDone new Error("website not found")
(err) ->
if err
done err
else
done()
)
], (err, results) ->
if err
next err
else
next()
When a user is deleted, it throws the error:
remove website { [VersionError: No matching document found.] message: 'No matching document found.', name: 'VersionError' }
I understand document versioning. I suspect that this bit of code in the Website and Card models is causing the issue.
...
cardSchema.pre 'remove', (next) ->
card = this
async.parallel [
# remove user association
(cb) ->
User.findById card.user, (err, user) ->
if err
cb err
else
# it could already be gone if this is a cascade
if user
user.cards = user.cards.filter (id) ->
"#{id}" isnt "#{card._id}"
user.save (err, user) ->
if err
cb err
else
cb()
else
cb()
], (err, results) ->
if err
next err
else
next()
So the user model is being updated during it's own middleware, by another function. I simply want the User model to has_many (Rails) cards and has_many websites. It's getting more and more complicated to maintain the relationship. I've considered nested schemas, but these particular documents are going to particularly middleware-heavy, plus I may want them to exist without the parent object.
Isn't there a better way?