试图在我的Web应用程序上创建一个新用户,却没有意识到我的数据库中已有一个用户具有相同的用户名 . 由于某种原因,这个边界情况打破了我的应用程序,现在每次我尝试去主页,我得到:

(node:14649)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):CastError:强制转换为ObjectId值为“{type:'Buffer',数据:[89,243,30,231,66,69,45 ,56,123,65,153,72]}“at path”_id“表示模型”users“(节点: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)位于/ Users / * / Desktop / coding的toError(/Users//Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/utils.js:139:22) /apps/thequoteapp/node_modules/mongodb/lib/collection.js:668:23 at handleCallback(/Users//Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/utils.js:120:56)at /用户/ * / Desktop / coding / apps / thequoteapp / node_modules / mongodb / lib / bulk / unordered.js:465:9 at handleCallback(/ Users / * / Desktop / coding / apps / thequoteapp / node_modules / mongodb / lib / utils .js:120:56)在/ Users / * / Desktop / coding / apps的resultHandler(/Users/*/Desktop/coding/apps/thequoteapp/node_modules/mongodb/lib/bulk/unordered.js:413:5) /thequoteapp/node_modules/mongodb-core/lib/connection/pool.js:469:18在_combinedTickCallback(internal / process / next_tick.js:131:7)at process._tick回调(internal / process / next_tick.js:180:9)名称:'MongoError',消息:'E11000重复键错误集合:crud2.users index:username_1 dup key:{:“lightbeam”}',driver:true,代码:11000,索引:0,错误:'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服务器的任何和所有实例 . 请帮忙!