mongoose的 .save方法如何解决 race condition的问题?
token.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TokenSchema = new Schema({
nickname: String,
token: {
type: String,
unique: true
}
}, {
collection: 'tokens'
});
var Token = mongoose.model('Token', TokenSchema);
module.exports = Token;
login.js
var crypto = require('crypto');
var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();
var User = require('../modules/user');
var Token = require('../modules/token');
router.get('/', function(req, res) {
res.render('login', {
title: '登录界面'
});
});
router.post('/', function(req, res) {
User.findOne({
tel: req.body.tel,
})
.exec(function(err, user) {
var md5 = crypto.createHash('md5'),
password = md5.update(req.body.password)
.digest('hex');
if (!user) {
return res.json({
success: false,
message: '认证失败,用户名找不到'
});
} else if (user.hash_password === password) {
return;
} else {
return res.json({
status: 007,
success: false,
message: '没有当前用户'
});
}
});
var tel = req.body.tel;
var user = new User({
tel: tel
});
var md5 = crypto.createHash('md5'),
password = md5.update(req.body.password)
.digest('hex');
user.set("hash_password", password);
user.set("name", req.body.name);
user.set("created_at", Date.now());
var token = jwt.sign(user, 'whuteditor', {
expiresIn: "30 days" // 设置过期时间
});
var tokenUser = new Token({
token: token
});
tokenUser.set("nickname", req.body.name);
tokenUser.save(function(err, token) {
if (err) {
return res.json({
status: 120,
success: false,
message: "Bad Storage"
});
} else {
res.json({
status: 100,
success: true,
message: 'Enjoy your token!',
token: token
});
}
});
});
module.exports = router;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论