模型文件中的功能成功运行。 但是要知道在注册期间ID是否重复并对其进行验证,我在函数中做了一个return语句。 服务器将根据分配给该功能的x值(在控制器文件中)进行响应。
//Model file
const bodyParser = require('body-parser');
const express = require('express');
const { check, validationResult } = require('express-validator');
const router = require('express').Router();
router.use(express.json());
const urlencoded = bodyParser.urlencoded({ extended: false });
const User = require('../DB/User.js'); //
function create_user(id1, name1, Password1) {
var user1 = new User({
id: id1,
name: name1,
Password: Password1
});
let x;
user1.save(function(err) {
if (err) {
if (err.code == 11000) {
x = 0;
console.log('user already exists and x= ' + x);
return x;
} else {
console.log(err);
}
} else {
x = 1;
console.log('Saved successfully and x =' + x);
return x;
}
})
}
module.exports = create_user;
//Controller file
const bodyParser = require('body-parser');
const express = require('express');
const { check, validationResult } = require('express-validator');
const { x } = require('joi');
const create_user = require('../model/Registration.js');
const router = require('express').Router();
router.use(express.json());
const urlencoded = bodyParser.urlencoded({ extended: false });
router.get('/Registration', function(req, res, next) {
res.render('Registration', { checker: 0 });
});
router.post('/Registraion/sign_up', function(req, res) {
let x = create_user(req.body.id, req.body.name, req.body.password);
console.log('x =' + x);
if (x == 0) {
req.body.id.setCustomValidity("This id is already used");
console.log('this id exsists and x =' + x); //the output here is x= undefined
} else {
res.redirect('/Registration');
}
});
module.exports = router;
答案 0 :(得分:1)
由于user1.save
是异步的,并且create_user
在返回之前不等待它解决,因此它返回null。
您可以使用callback
或async await
模式解决该问题
尝试一下:
function create_user(id1, name1, Password1, callback) {
var user1 = new User({
id: id1,
name: name1,
Password: Password1
});
let x;
user1.save(function(err) {
if (err) {
if (err.code == 11000) {
x = 0;
console.log('user already exists and x= ' + x);
callback(x);
return x;
} else {
console.log(err);
}
} else {
x = 1;
callback(x);
console.log('Saved successfully and x =' + x);
return x;
}
})
}
//Controller file
router.post('/Registraion/sign_up', function(req, res) {
create_user(req.body.id, req.body.name, req.body.password, function(x) {
console.log('x =' + x);
if (x == 0) {
req.body.id.setCustomValidity("This id is already used");
console.log('this id exsists and x =' + x); //the output here is x= undefined
} else {
res.redirect('/Registration');
}
});
});