试图在我的网络应用程序上创建一个新用户,却没有意识到我的数据库中已有一个用户具有相同的用户名。出于某种原因,这个边界案例打破了我的应用程序,现在每当我尝试去主页时,我得到:
(node:14649)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):CastError:对于值“{type:'Buffer',Cast to ObjectId失败, 数据:[89,243,30,231,66,69,45,56,123,65,153,72]}“在路径”_id“为模型”用户“ (节点:14649)[DEP0018]弃用警告:不推荐使用未处理的拒绝承诺。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。
这个问题与stackoverflow中的其他问题的独特之处在于,该类型是“缓冲区”。没有其他问题有这个具体问题。我不知道在我的数据库或节点服务器中根本不使用缓冲区时是如何创建缓冲区的。
以下是缓冲区错误之前发生的重复错误消息:
{MongoError:E11000重复键错误集合:crud2.users index:username_1 dup key:{:“lightbeam”} 在Function.MongoError.create(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb-core/lib/error.js:31:11) 在toError(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/utils.js:139:22) at /Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/collection.js:668:23 在handleCallback(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/utils.js:120:56) at /Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/bulk/unordered.js:465:9 在handleCallback(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/utils.js:120:56) at resultHandler(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/bulk/unordered.js:413:5) at /Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb-core/lib/connection/pool.js:469:18 at _combinedTickCallback(internal / process / next_tick.js:131:7) at process._tickCallback(internal / process / next_tick.js:180:9)name:'MongoError',message:'E11000重复键错误集合: crud2.users index:username_1 dup key:{:“lightbeam”}',driver: true,代码:11000,index:0,errmsg:'E11000重复键错误 集合:crud2.users index:username_1 dup key:{:“lightbeam”}', getOperation:[Function],toJSON:[Function],toString:[Function] }
这是我的用户架构:
const express = require('express')
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let UserSchema = new Schema ({
username: {
type: String,
unique: [true, "This username is taken."],
trim: true
},
email: {
type: String,
unique: [true, "This email is already being used."],
trim: true
},
password: {
type: String,
trim: true
}
}, {
timestamps: true,
favorites: []
})
// first parameter is the name of the collection! If does not exist, will be created!
const User = mongoose.model('users', UserSchema)
module.exports = User
这是我的route.js文件中定义的get请求:
/* route handling for HOME PAGE. */
router.get('/', (req, res, next) => {
console.log("req.user value: ", req.user)
Quote.find({})
.exec((err, results) => {
err ? console.log(err) : res.render('index', { quotes: results })
})
})
最后是创建新用户的帖子请求:
router.post('/signup/users', (req, res, next) => {
req.checkBody('username', 'Username field cannot be empty.').notEmpty()
req.checkBody('username', 'Username must be between 4-30 characters long.').len(4, 30)
req.checkBody('email', 'The email you entered is invalid, please try again.').isEmail()
req.checkBody('email', 'Email address must be between 4-100 characters long, please try again.').len(4, 100)
req.checkBody('password', 'Password must be between 8-100 characters long.').len(8, 100)
// req.checkBody('password', 'Password must include one lowercase character, one uppercase character, a number, and a special character.').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i')
req.checkBody('passwordMatch', 'Password must be between 8-100 characters long.').len(8, 100)
req.checkBody('passwordMatch', 'Passwords do not match, please try again.').equals(req.body.password)
// Additional validation to ensure username is alphanumeric with underscores and dashes
req.checkBody('username', 'Username can only contain letters, numbers, or underscores.').matches(/^[A-Za-z0-9_-]+$/, 'i')
const errors = req.validationErrors()
if(errors) {
res.render('signup', {
errors: errors
})
} else {
let password = req.body.password
bcrypt.hash(password, saltRounds, (err, hash) => {
user = new User()
user.username = req.body.username
user.email = req.body.email
user.password = hash
user.save((err, result) => {
if(err) {
console.log(err)
} else {
User.find({}).sort({ _id:-1 }).limit(1)
.exec((err, newuser) => {
if (err) {
console.log(err)
} else {
userId = ObjectId(newuser.id)
// logins user through passport function
req.login(userId, (err) => {
if (err) {
console.log("Login error: " + err)
} else {
res.redirect('/home')
}
})
}
})
.catch(next)
}
})
})
}
})
我尝试重新启动nodemon和mongodb服务器,我尝试使用:
kill -2 `pgrep mongo`
清除mongodb服务器的所有实例。请帮忙!