Node.js ORM2 检查字段是不是已存在
Posted
技术标签:
【中文标题】Node.js ORM2 检查字段是不是已存在【英文标题】:Node.js ORM2 check if field already existsNode.js ORM2 检查字段是否已存在 【发布时间】:2014-01-18 17:10:44 【问题描述】:检查字段值是否已存在的最佳方法是什么。
这是我的模型:
// Set global
var moment = require('moment');
var _ = require('lodash');
// Create model
module.exports = function (orm, db)
var Profile = db.define('profile',
// Field Properties
username: type: 'text', required: true, unique: true,
name: type: 'text', required: true,
email: type: 'text', required: true,
password: type: 'text', required: true,
birthday: type: 'date', required: true,
gender: type: 'enum', values: ["male", "female"], required: true,
join_date: type: 'date'
,
// Model hooks. Manual: https://github.com/dresende/node-orm2/wiki/Model-Hooks
hooks:
beforeValidation: function()
// Set join date to current date
this.join_date = new Date();
,
// Model Validations. Manual: https://github.com/dresende/node-orm2/wiki/Model-Validations
validations:
username: [orm.enforce.security.username(length: 4, 'Invalid username')],
email: [orm.enforce.patterns.email('Please enter a valid email')],
password: [orm.enforce.security.password('6', 'Invalid password')],
birthday: [orm.enforce.patterns.match(/\d2-\d2-\d4/, null, 'Invalid birthday')]
,
// Model methods. Extra functions and stuff
methods:
);
;
这是我的注册控制器:
module.exports = function (req, res, next)
// Get post params
var params = _.pick(req.body, 'formAction', 'username', 'password', 'email', 'confirm_password',
'birthday', 'gender', 'terms');
// If we try to register
if (params['formAction'] == 'register')
// Manual validations
// Check if we agreed with the terms
if (params['terms'] != 1)
res.send(error: 'You must agree to the terms of service');
return false;
// Check if password was confirmed
if (params['password'] && params['password'] != params['confirm_password'])
res.send(error: 'Please confirm your password');
return false;
// Check if username already exists
// Try to register
req.models.profile.create(username: params['username'],
password: params['password'],
email: params['email'],
birthday: params['birthday'],
gender: params['gender'],
name: params['username'], function (err, items)
// Check to see if we have error
error = helpers.getError(err);
// Return error
if (error)
res.send(error: error);
);
// Show login form
else
res.sendfile(settings.path + '/public/register.html');
;
如何检查数据库中是否已经存在用户名?现在,如果我尝试创建,我会从数据库中得到 DUP_KEY 错误。
谢谢, 拉度
【问题讨论】:
【参考方案1】:看起来像添加一个钩子并使用 next() 解决了
beforeCreate: function (next)
obj = this;
Profile.exists(email: this.email, function (err, exists)
if (exists)
return next(new Error("Email already exists"));
else
Profile.exists(username: obj.username, function (err, exists)
console.log(exists);
if (exists)
return next(new Error("Username already exists"));
else
return next();
);
);
【讨论】:
以上是关于Node.js ORM2 检查字段是不是已存在的主要内容,如果未能解决你的问题,请参考以下文章
检查 Flutter Firestore 中是不是已存在字段
Node.js、discord.js 和 MySQL - ER_NO_SUCH_TABLE:表 'NAME' 不存在