我有node.js代码,并且使用猫鼬。我没发现任何错误,只是Successfuly logged in
。
几天来,我正试图解决这个问题,我尝试了很多事情,但没有一个起作用。
这是服务器代码:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const model = require('.//models/schema');
app.use(express.static('public'));
app.get('/register', function(request, response) {
response.sendFile(__dirname + '/html/register.html');
});
app.get('/login', function(request, response){
response.sendFile(__dirname + '/html/login.html')
});
const listener = app.listen(3000, function() {
let myURL = new URL(`localhost:${listener.address().port}/register`);
console.log(myURL.href);
});
mongoose.connect(`mongodb://localhost${listener.address().port}:/register`, {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.post('/submit-data', async (req, res) => {
res.redirect('/login')
try {
const newUser = new model({
'login': req.body.login,
'password': req.body.password,
'gender': req.body.gender,
'birthday': req.body.birthday
});
await newUser.save();
console.log('User registered');
} catch {
console.log('Registeration failed')
}
});
app.post('/submit-login', (req, res) => {
const user = model.findOne({
'login': req.body.login,
'password': req.body.password,
});
if (!user) {
console.log('Login failed');
} else {
console.log('Successfully logged in')
}
});
这是模型代码:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let schema = new Schema({
'login': String,
'password': String,
'gender': String,
'birthday': String
});
module.exports = mongoose.model('allInfo', schema);
如果密码或登录名不同,我希望它打印“登录失败”,如果密码和登录名相同,则希望打印“成功登录”。
答案 0 :(得分:0)
您需要查看docs
您应将条件移至回调,如下所示:
const user = model.findOne({
'login': req.body.login,
'password': req.body.password,
}, function (err, user) {
if (!user) {
console.log('Login failed');
} else {
console.log('Successfully logged in')
}
}));
第一个参数是您的模型所针对的集合的单数名称。猫鼬会自动寻找模型名称的复数形式,小写形式。
这意味着在您的代码中,模型将寻找名为allinfos
的集合,如果数据库中的表名为users
,则应更改此行
module.exports = mongoose.model('allInfo', schema);
对此:
module.exports = mongoose.model('User', schema); // This will look-up the collection users