0
votes
    var categoryList = new Referral({categoryList : category});

    categoryList.pre('save', function (next) {
        Referral.find({categoryList : category}, function (err, docs) {
            if (!docs.length){
                next();
            }else{
                console.log('Data exists: ', category);
                next(new Error("Data exists!"));
            }
        })
    })

Referral is my variable assigned to my schema. categoryList is the object

This gives an error

TypeError: categoryList.pre is not a function at D:\Aventyn\ClipCare_v2\app\api.js:112:18 at Layer.handle [as handle_request] (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5) at next (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5) at D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:277:22 at Function.process_params (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:330:12) at next (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:271:10) at Function.handle (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:176:3) at router (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:46:12) at Layer.handle [as handle_request] (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:312:13) at D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:280:7 at Function.process_params (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:330:12) at next (D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:271:10) at D:\Aventyn\ClipCare_v2\node_modules\express\lib\router\index.js:618:15

2

2 Answers

4
votes

Try changing:

categoryList.pre('save', function (next) {
  // ...
})

to:

categoryList.schema.pre('save', function (next) {
  // ...
})

The .pre() is a method of the Mongoose schema, not a model.

0
votes

Middleware (like pre hooks) are part of a schema. It looks like you're trying to use it on a single document, which is not how it works.

Instead, use it on the schema that you used to create the Referral model:

ReferralSchema.pre('save', ...);

This does mean that the pre hook will be applied to all documents of that schema.