我正在尝试检查用户是否存在save
调用的预挂钩。这是我的模型的架构:
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"
}
}
对我的问题可能有什么建议吗?
答案 0 :(得分:1)
find()
函数属于model
,而不属于schema
您需要生成一个模型并在其上运行find:
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;