gpt4 book ai didi

javascript - 如何仅针对创建用户页面而不是编辑用户页面执行 Mongoose 验证功能?

转载 作者:行者123 更新时间:2023-11-30 10:03:36 24 4
gpt4 key购买 nike

背景
我目前正在使用 Node.js、Express 和 MongoDB 构建一个网站。我正在使用 mongoose 来处理我的 MongoDB 服务器。现在,我的 Mongoose 模式中有一个函数可以检查用户输入的电子邮件地址是否已存在于数据库中。我希望此功能仅在创建帐户页面上被调用。任何帮助将不胜感激!谢谢!

问题
该功能运行良好,但在编辑用户个人资料页面和创建用户页面上都会被调用。这意味着如果用户不在编辑个人资料页面上更改他们的电子邮件,他们将无法更新他们的个人资料。我只希望为创建用户页面调用此验证唯一电子邮件功能,这样我就可以避免这个问题。如何根据用户所在的页面运行功能?

代码
在我的用户模式中检查电子邮件是否已存在的函数

UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');

整个用户架构(文件名为 user.server.model.js)

'use strict';

/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
crypto = require('crypto');

/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function(property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
* A Validation function for local strategy password
*/
var validateLocalStrategyPassword = function(password) {
return (this.provider !== 'local' || (password && password.length > 6));
};

/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
},
companyName: {
type: String,
trim: true,
default: ''
},
companyWebsite: {
type: String,
trim: true,
default: ''
},
companyAddress1: {
type: String,
trim: true,
default: ''
},
companyAddress2: {
type: String,
trim: true,
default: ''
},
companyCity: {
type: String,
trim: true,
default: ''
},
companyState: {
type: String,
trim: true,
default: ''
},
companyZip: {
type: String,
trim: true,
default: ''
},
phone: {
type: String,
trim: true,
default: ''
},
email: {
type: String,
trim: true,
default: '',
unique: true,
validate: [validateLocalStrategyProperty, 'Please fill in your email'],
match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
username: {
type: String,
unique: 'testing error message',
required: 'Please fill in a username',
trim: true
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be longer']
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user']
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
}
});

/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}

next();
});

/**
* Check if email already exists in database
*/
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');

/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};

/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};

/**
* Find possible not used username
*/
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');

_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};

mongoose.model('User', UserSchema);

users.server.routes.js 文件

'use strict';

/**
* Module dependencies.
*/
var passport = require('passport');

module.exports = function(app) {
// User Routes
var users = require('../../app/controllers/users.server.controller');

// Setting up the users profile api
app.route('/users/me').get(users.me);
app.route('/users').put(users.update);
app.route('/users/accounts').delete(users.removeOAuthProvider);

// Setting up the users password api
app.route('/users/password').post(users.changePassword);
app.route('/auth/forgot').post(users.forgot);
app.route('/auth/reset/:token').get(users.validateResetToken);
app.route('/auth/reset/:token').post(users.reset);

// Setting up the users authentication api
app.route('/auth/signup').post(users.signup);
app.route('/auth/signin').post(users.signin);
app.route('/auth/signout').get(users.signout);

// Finish by binding the user middleware
app.param('userId', users.userByID);
};

最佳答案

您可以使用 Document.isNew 标志仅在创建时运行检查。像这样:

UserSchema.pre('save', function(next) {
if (this.isNew) {
// Enforce constraints here
}

if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}

next();
});

您还可以随意使用 Document.isModified,因此在您的保存 Hook 中您也可以检查 this.isModified('email')

关于javascript - 如何仅针对创建用户页面而不是编辑用户页面执行 Mongoose 验证功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30416170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com