我正在尝试使用节点js和mongo db实现登录api,但不幸的是 我总是得到空的回复或“无法读取未定义的属性密码”。 当我做CurrentUser.find()。exec(function(err,user){}); - 它确实带来了我的所有收藏。
我有这种模式:
users.js:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const UserSchema = Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true }
});
module.exports = mongoose.model('User', UserSchema);
我的router.js:
const mongoose = require('mongoose');
const AlbuMmodel = require('../src/lib/models/album');
const UserModel = require('../src/lib/models/users');
const CurrentUser = require('../src/lib/models/users');
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const cookieParser = require('cookie-parser');
mongoose.connect('mongodb://localhost/shopdb');
mongoose.Promise = global.Promise;
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser('secret'));
app.use(session({secret: 'qwerty', saveUninitialized: true, resave: false}));
exports.loginUser = function (req, res){
var useremail = req.body.email;
var psw = req.body.password;
CurrentUser.find({email:useremail}).exec(function(err, user) {
if(err){
return res.send({"status":"500","message":"There is a problem. Please try later"});
}
if(!user){
return res.send({"status":"410", "message":"Invalid password or email"});
}
if (!err) {
if(psw == user[0].password){
req.session.user = user;
return res.send(user[0]);
}
else{
return res.send({"status":"410", "message":"Invalid password or email"});
}
}
else{
req.session.reset();
return res.send({"status":"400", "message":"Invalid password or email"});
}
});
};
在数据库集合中保存并命名为:users