我有这个代码检查是否已经使用了用户名(存储在json文件中)现在它从json文件中获取数据。我怎么能这样做,但从mongodb集合中获取数据?有可能吗?
提前致谢。
var userList;
$.getJSON("/usernames.json", function(data) {
userList=data.map(function(user){ return user.username});
})
function validateUserList() {
return $.inArray($('#username').val(), userList) > -1
}
$(function() {
$(':input[name=username]').blur(function() {
if (!validateUserList()) {
$('div#validUser').text('');
} else {
$('div#validUser').text('Username is already taken.');
}
});
});
这是注册用户的Node.js代码
我将数据保存到2个不同的集合中,I.d喜欢只从用户名集合中获取数据。
// Register Proccess
router.post('/register', upload.single('avatar'), function(req, res){
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
const password2 = req.body.password2;
const date = new Date();
if(req.file){
var avatar = req.file.filename;
} else {
var avatar = 'noimage.png';
}
// check to make sure this user hasnt registered
var testThisName = username;
var queryforUsername = {};
queryforUsername["username"] = testThisName;
Username.find(queryforUsername, function(error,item) {
if(error) throw error;
if(item.length > 0) {
req.flash('warning', 'That username is already taken!')
res.redirect('/users/register');
} else if (item.length == 0) {
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
let {errors, validationResults} = require('express-validator');
if(errors){
res.render('register', {
errors:errors
});
} else{
let newUser = new User({
username:username,
email:email,
password:password,
date: date,
avatar: avatar
});
let newUsername = new Username({
username:username,
});
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
if(err){
console.log(err);
}
newUser.password = hash;
newUser.save(function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success','You are now registered and can log in');
res.redirect('/');
}
});
newUsername.save(function(err){
if(err){
console.log(err);
return;
}
});
});
});
}
}
})
});