0

I'm trying to check if a user exists in a pre-hook to the save call. This is the schema for my model:

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

var empSchema = new Schema({
    name: String,
    img: String,
    info: String,
    mobnum: String,
    email: String,
    likes: [String]
},
{
    collection: "employers"
}
);


empSchema.pre('save', function(next) {
    var self = this;
    empSchema.find({email: self.email}, function(err, docs) {
        if(!docs.length()){
            next();
        }
        else {
            next(new Error("User exists."));
        }
    });
});

module.exports = mongoose.model('Employer', empSchema);

This gives me the following error:

/home/gopa2000/prog/android_workspace/MobAppsBE/app/models/employer.js:21
    empSchema.find({email: self.email}, function(err, docs) {
              ^

TypeError: empSchema.find is not a function

Package.json:

{
  "name": "tjbackend",
  "version": "1.0.0",
  "description": "REST API for backend",
  "dependencies": {
    "express": "~4.5.1",
    "mongoose": "latest",
    "body-parser": "~1.4.2",
    "method-override": "~2.0.2",
    "morgan": "~1.7.0"
  },
  "engines": {
    "node":"6.4.0"
  }
}

Any suggestions to what my issue may be?

doberoi96
  • 413
  • 6
  • 22
  • 1
    hmm... is emp**Schema** a model? it looks like a *schema* to me. – Kevin B Nov 14 '16 at 22:13
  • http://stackoverflow.com/questions/16882938/how-to-check-if-that-data-already-exist-in-the-database-during-update-mongoose I'm following the method under "Update 2" of the accepted answer. I'm calling save from a different controller file. – doberoi96 Nov 14 '16 at 22:18
  • 1
    You don't appear to be following said method very closely. `User` is not the same as `userSchema` – Kevin B Nov 14 '16 at 22:19
  • Ouch. Yes, you're right. Gone a bit too far into the night. :-) Thanks! – doberoi96 Nov 14 '16 at 22:22

1 Answers1

1

find() function belongs to model, not to schema.
You need to generate a model and run find on it:

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

var empSchema = new Schema({
    name: String,
    img: String,
    info: String,
    mobnum: String,
    email: String,
    likes: [String]
},
{
    collection: "employers"
}
);

var employer = mongoose.model('Employer', empSchema);

empSchema.pre('save', function(next) {
    var self = this;
    employer.find({email: self.email}, function(err, docs) {
        if(!docs.length()){
            next();
        }
        else {
            next(new Error("User exists."));
        }
    });
});

module.exports = employer;
Nir Levy
  • 12,750
  • 3
  • 21
  • 38