gopa2000 gopa2000 - 24 days ago 6
Node.js Question

Model.find() in not a function ExpressJS

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?

Answer

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;