2016-11-14 16 views
0

我試圖檢查一個用戶是否存在於save調用的預鉤中。這是我的模型架構:Model.find()不是函數ExpressJS

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

這給了我下面的錯誤:

/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" 
    } 
} 

一下我的問題可能是有什麼建議?

+1

嗯...是EMP ** **架構的模型?它看起來像一個* schema *給我。 –

+0

http://stackoverflow.com/questions/16882938/how-to-check-if-that-data-already-exist-in-the-database-during-update-mongoose 我正在按照「更新2「的接受答案。我從另一個控制器文件調用保存。 – doberoi96

+1

你似乎沒有非常密切地關注上述方法。 'user'與'userSchema'不一樣。 –

回答

1

find()功能屬於model,而不是schema
你需要生成一個模型並找到它:

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;