我有以下模块,
module.exports.registerUser = (userData) => {
return new Promise((resolve, reject) => {
if (userData.password !== userData.password2) {
reject("Passwords do not match!");
}
console.log(userData); //prints correctly
let newUser = new iUser(userData);
console.log(newUser); //prints correctly
newUser.save((err) => {
console.log("REACHED"); //DOES NOT ENTER
if (err) {
reject(err.code === 11000 ? 'Username already taken!' :
`Error creating User: ${err}`);
} else {
console.log(newUser);
resolve(newUser);
}
process.exit();
});
})
};
出于某种原因,.save()
永远不会被调用,第10行永远不会到达......有什么想法吗?
使用registerUser()
模块,到目前为止我的data-service-auth.js
源文件是:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var userSchema = new Schema({
"userName": {
type: String,
unique: true
},
"email": String,
"password": String,
"loginHistory": {
"userAgent": String,
"dateTime": Date
}
});
let iUser;
module.exports.initialize = () => {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection("mongodb://user:pass@ds237409.mlab.com:37409/web322_a6");
db.on('error', function (err) {
console.log("error!");
reject(err);
});
db.once('open', function() {
console.log("enteringgggggggggggg");
iUser = mongoose.model("iUser", userSchema);
resolve();
});
resolve();
});
};
module.exports.registerUser = (userData) => {
return new Promise((resolve, reject) => {
if (userData.password !== userData.password2) {
reject("Passwords do not match!");
}
console.log(userData);
let newUser = new iUser(userData);
newUser.save((err) => {
console.log("REACHED"); //DOES NOT ENTER
if (err) {
reject(err.code === 11000 ? 'Username already taken!' :
`Error creating User: ${err}`);
} else {
console.log(newUser);
resolve(newUser);
}
process.exit();
});
})
};
我的注册表格POST到我的server.js
文件,该文件有一条路线
app.post("/register", (req, res) => {
dataServiceAuth.registerUser(req.body).then((data) => {
res.render('register', {successMessage: "User Created"});
}).catch((err) => {
console.log("Error: " + err);
res.render('register', {errorMessage: err, userName: req.body.userName});
})
});
我的register.hbs
视图是,(如果格式化很糟糕,这里有新编码器道歉):
<h2>Register</h2>
<hr />
<form method="post" action="/register">
{{!-- form --}}
</form>
{{#if errorMessage }}
<div class="alert">
<strong>Error:</strong> {{errorMessage}}</div>
{{else if successMessage}}
<div class="success">
<strong>Success:</strong> {{successMessage}}
</div><a class="btn-right"
href="/login">Proceed to Log in</a>
<br />
<br />
<br />
{{/if}}
我认为它必须是.save()
函数,因为永远不会到达并执行console.log("REACHED");
,但是在创建该实例后调用console.log(userData)
或console.log(newUser);
会产生预期的结果结果