node.jsmongodbangularmongoosemongoose-middleware

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?


Solution

  • 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);
    

    });