我一直试图使用mongoose将带有用户名和令牌的文档保存在mongodb数据库中。每当客户端向服务器发出请求时,令牌都会更新并保存在数据库中。要更新文档,我要使用用户名(因为它是唯一的)查询集合,然后更新返回的文档的(例如doc)令牌字段,然后调用doc.save()。问题是doc.save()交替给我用户名验证错误(即,在第一次尝试和第三次尝试中都起作用,依此类推...),但在第二次尝试,第四次尝试中均失败。
如果我删除了用户名验证约束,那么代码将起作用,但是由于明显的原因,我无法删除验证约束。
usermodel.js
let mongoose = require('mongoose');
let user = new mongoose.Schema({
username: {
type: String,
match: /^[A-Za-z0-9_]+$/g,
unique: true,
required: true,
},
password: {
type: String,
match: /.{8,}/g,
required: true,
},
token: String
});
module.exports = mongoose.model('user', user);
getData.js
module.exports = async function putData(database, model, query, fields, queryType='one'){
let mongoose = require('mongoose');
const connectionURL = `mongodb://127.0.0.1:27017/${database}`;
mongoose.connect(connectionURL, {
useNewUrlParser: true,
useCreateIndex: true
});
return model.init().then(async ()=>{
let res;
switch(queryType){
case 'one':
res = await model.findOne(query).select(fields).exec();
break;
case 'all':
res = await model.find(query).select(fields).exec();
}
return res;
})
}
putData.js
module.exports = async function putData(database, model, data){
let mongoose = require('mongoose');
const connectionURL = `mongodb://127.0.0.1:27017/${database}`;
mongoose.connect(connectionURL, {
useNewUrlParser: true,
useCreateIndex: true
});
return model.init().then(async ()=>{
console.log('Username is, ', data.username);
let prom = await data.save();
return prom;
});
}
updateToken.js
let user = require('../models/users-model');
let putData = require('../putData');
let bcrypt = require('bcrypt');
let getData = require('../getData');
function update_token(username, token, callbackfn){
getData('users', user, {
username: username,
token: token
}, 'username token').then((userData)=>{
console.log(userData);
if(userData){
bcrypt.hash(JSON.stringify(userData), 5).then((hash)=>{
userData.token = hash;
return putData('users', user, userData, true);
}).then((data)=>{
callbackfn(null, data);
}).catch((err)=>{
//console.log(err);
callbackfn(err, null);
})
}
else{
callbackfn(new Error('Invalid token'), null);
}
}).catch((err)=>{
console.log(err);
callbackfn(err, null);
})
}
module.exports = {
update_token: update_token
}
server.js
let express = require('express');
let app = express();
let usersRouter = require('./routers/users');
let tourMakerRouter = require('./routers/tour-maker');
let bodyparser = require('body-parser');
let utils = require('./utils/utils');
let getData = require('./getData');
let user = require('./models/users-model');
const host = '127.0.0.1';
const port = 8000;
let jsonencodedparser = bodyparser.json();
app.post('/', jsonencodedparser, (req, res)=>{
console.log('Request received!');
utils.update_token(req.body.username, req.body.token, (err, data)=>{
if(err){
console.log(err);
if(err.message === 'Invalid token'){
res.status(401).end();
}
res.status(500).end();
}
else{
res.json({
token: data.token,
username: data.username
});
}
})
})
app.listen(port, host, ()=>{
console.log(`Listening at http://${host}:${port}`);
})
第一个请求
Request received!
{ _id: 5cdadbdfeeb7c02610b14f1a,
username: 'user1',
token: '$2b$05$oHkFuyW532Yq6p2o04TumeAON8SBtIL/lZ.Kty1gX2lqHqnMEI/Pa' }
Username is, user1
第二个请求:
Request received!
{ _id: 5cdadbdfeeb7c02610b14f1a,
username: 'user1',
token: '$2b$05$gaS5U4kRiVqCShKbiZe/t.LTUBTh5H7AAE7p2MXIUW65xezbPslG2' }
Username is, user1
{ ValidationError: user validation failed: username: Path
用户名is invalid (user1).
at ValidationError.inspect (/home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/error/validation.js:59:24)
at formatValue (util.js:430:38)
at inspect (util.js:324:10)
at format (util.js:191:12)
at Console.log (console.js:130:21)
at utils.update_token (/home/arpit/Study/Projects/tour-maker/server/server.js:18:21)
at bcrypt.hash.then.then.catch (/home/arpit/Study/Projects/tour-maker/server/utils/utils.js:20:17)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
errors:
{ username:
{ ValidatorError: Path
用户名is invalid (user1).
at new ValidatorError (/home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/error/validator.js:29:11)
at validate (/home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/schematype.js:978:13)
at /home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/schematype.js:1031:11
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (/home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/schematype.js:987:14)
at /home/arpit/Study/Projects/tour-maker/node_modules/mongoose/lib/document.js:2101:9
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
message: 'Path
用户名is invalid (user1).',
name: 'ValidatorError',
properties: [Object],
kind: 'regexp',
path: 'username',
value: 'user1',
reason: undefined,
[Symbol(mongoose:validatorError)]: true } },
_message: 'user validation failed',
name: 'ValidationError' }
感谢您的帮助。 预先感谢!
答案 0 :(得分:-1)
我没有足够的声誉来发表评论,但是您是否尝试过每次检查请求以查看作为用户名实际发送的内容?出于某些原因可能存在一些验证问题。