Stevin29
Stevin29

Reputation: 75

Mongoose Middleware pre 'remove' doesn't work, Model.update is not a function

I have a middleware query set up for a Book schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User= require('./user');

var schema = new Schema({

    name : {type: String, required:true},
    startDate: {type: Date},// UTC datetime
    endDate: {type: Date},// UTC datetime
    status: {type: String},
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});


schema.post('remove', function(next) {

    User.update(
        { books: this._id},
        { $pull: { books: this._id } })
        .exec();
    next();
});

module.exports = mongoose.model('Book', schema);

As you can see it tries to remove the book from the user's list of books. For reference see User schema (the post query in this one works by the way):

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Book = require('./book');

var schema = new Schema({

    firstName: {type: String, required: true},
    lastName: {type: String},
    phone1: {type: String},
    phone2: {type: String},
    email: {type: String},
    address: {type: Schema.Types.ObjectId, ref: 'Address'},
    books: [{type: Schema.Types.ObjectId, ref:'Book'}]
});

schema.post('remove', function (user) {
    Book.findById({$in : user.books}, function (err, book) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred cascade delete operations for user',
                error: err
            });
        }

        if (book) {
            book.user= undefined;
            book.save();
        }

    });
});
module.exports = mongoose.model('User', schema);

I keep on getting this error, I tried numerous of variations in the query but to no avail:

process.nextTick(function() { throw err; });
TypeError: User.update is not a function

Can someone please help me out?

Upvotes: 1

Views: 3614

Answers (2)

Steve Holgado
Steve Holgado

Reputation: 12081

This could be down to a circular dependency due to importing each model into the other using require().

Try replacing the use of require() to import your models:

var User = require('./user')

...and:

var Book = require('./book')

Instead, get the model from mongoose at the point you need to use it, for example:

mongoose.model('User').update(...)

...and:

mongoose.model('Book').findById(...)

Also note that you will likely need to import both modules using require() in the file where you plan to use them, in order to register both models with mongoose before use.

I hope this helps.

Upvotes: 2

Richard Lovell
Richard Lovell

Reputation: 888

I think you should use .pre() instead. Hopefully something like this will work for you:

bookSchema.pre('remove', function (next) {
var book = this;
book.model('User').update(
    { books: book._id }, 
    { $pull: { books: book._id } }, 
    { multi: true }, 
    next);

});

Upvotes: 3

Related Questions