shuk
shuk

Reputation: 1823

mongoose model.update not working

It used to work before. I do not know what changed... This is the method:

User has an Array of teams. Once A Team is deleted, I wish for the RefID to be removed as well from the user's Team array

TeamSchema.pre('remove', function(next) {
  const team = this;
  User.update( { teams: { $in: [team._id] } }, { $pull: { teams: team._id } }, next);
});

getting this error:

(node:7484) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: User.update is not a function

Also, None of the other methods work as well (Model.findById, Model.find, etc...), although I do have my model and mongoose imported at the top of the file.

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

Somehow none of my mongoose operations work within that Model.pre() function.

I have another file with a pre method, in which the Model.find function works:

UserSchema.pre('remove', function(next) {
  const user = this;
  Team.find({ admin: { $in: [user._id] } }, function(err, teams) {
    if (err) {
      return next(err);
    }
    teams.forEach(function(t) {  t.remove(); });
    next
  });
});

Is anyone familiar with this issue?

Upvotes: 0

Views: 629

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can try using mongoose.models[modelName] instead of direct model name. like bellow

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var UserSchema = new Schema({
     // .....
    })

UserSchema.pre('remove', function(next) {
  const user = this;
  mongoose.models['Team'].find({ admin: { $in: [user._id] } }, function(err, teams) {
    if (err) {
      return next(err);
    }
    teams.forEach(function(t) {  t.remove(); });
    next();
  });
});

and Team model should exported with name Team. like:

module.exports = mongoose.model('Team', TeamSchema);

Upvotes: 2

Related Questions