gpt4 book ai didi

javascript - Express/JavaScript 中的作用域和传递 - 如何传递数据库变量?

转载 作者:行者123 更新时间:2023-11-29 23:00:56 25 4
gpt4 key购买 nike

<分区>

我正在尝试设置一个动态注册页面,通过在 keyUp 上获取电子邮件值并通过 Mongoose 将其与 MongoDB 检查来检查帐户是否存在。

这是 Pug 页面:

html
include head.pug
script
include ../register.js
include navbar.pug
body
form(action = "/register", method = "POST")
div.form
p#pnotice
label(for = "firstname") First Name
br
input(name = "firstname")
br
br
label(for = "lastname") Last Name
br
input(name = "lastname")
br
br
label(for = "email") E-Mail
br
input#email(name = "email")
br
br
label(for = "password") Password
br
input#pass1(name = "password" type = "password")
br
br
label(for = "passwordc") Password Confirmation
br
input#pass2(name = "passwordc" type = "password")
br
br
button(type = "submit") Register

然后是注册码,密码校验功能运行正常,但是User.findOne()函数根本不起作用:

$(document).ready(function() {
$('#pass2').keyup(function() {
let p1 = $('#pass1').val();
let p2 = $('#pass2').val();
if (p1 !== p2) {
$('#pnotice').show();
$('#pnotice').text('Password Must Match');
} else {
$('#pnotice').hide();
}
});

$('#email').keyup(function() {
//alert($('#email').val());
let query = $('#email').val();
User.findOne({email: query}, function(err, res) {
if (res) {
console.log("FOUND");
} else {
console.log("NOT FOUND");
}
});
})
});

这是我的 Express 中的相关代码:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');

var userSchema = mongoose.Schema({
firstname: String,
lastname: String,
email: String,
password: {
type: String,
required: true,
bcrypt: true
},
teacher: String,
time: Number
});

var User = mongoose.model("User", userSchema);

我真的很陌生,所以我想我犯了一个菜鸟错误,但我假设 User 变量超出了 register.js 文件的范围,因为它是一个单独的文件。有没有办法传递变量或给它一个更大的范围,以便所有文件都可以访问它?还是我这样做完全不正确?

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