当我在使用mongoose的NodeJ中没有findbyid或任何东西时,为什么会因为值错误而获取objectid失败

beq87vna  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(149)

所以问题是,当我尝试点击我的“用户”端点(与用户有关的一切)时,我得到了一个错误或不是真正的错误,它只是取消了呼叫,没有任何解释,然后我尝试在一个新的点击中打开请求,在这里给我你在屏幕截图中看到的解释。
奇怪的是,我的其他端点在浏览器中工作,“用户”端点在postman中工作得非常好,但在浏览器中,它给了我这个错误。

我的用户模型

const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Pleas tell us your name'],
    },
    email: {
        type: String,
        required: [true, 'Please provide us your email'],
        unique: true,
        lowercase: true,
        validate: [validator.isEmail, 'Please provide a valid email']
    },
    photo: {
        type: String,
        default: 'default.jpg'
    },
    password: {
        type: String,
        required: [true, 'Please provide a password'],
        minlength: 8,
        select: false
    },
    passwordConfirm: {
        type: String,
        required: [true, 'Please confirm your password'],
        validate: {
            //This only works on CREATE and SAVE!!!
            validator: function (el) {
                return el === this.password;
            },
            message: 'Passwords are not the same'
        }
    },
    passwordChangedAt: Date,
    passwordResetToken: String,
    passwordResetExpires: Date,
    active: {
        type: Boolean,
        default: true,
        select: false
    }
});

userSchema.pre('save', async function (next) {
    if (!this.isModified('password')) return next();

    this.password = await bcrypt.hash(this.password, 12);

    this.passwordConfirm = undefined;
    next();
});

userSchema.pre('save', function (next) {
    if (!this.isModified('password') || this.isNew) return next();

    this.passwordChangedAt = Date.now() - 1000;
    next();
});

userSchema.pre(/^find/, function (next) {
    //This points to the current query
    this.find({
        active: {
            $ne: false
        }
    });
    next();
});

userSchema.methods.correctPassword = async function (candidatePassword, userPassword) {
    return await bcrypt.compare(candidatePassword, userPassword);
}

userSchema.methods.changedPasswordAfter = function (JWTTimestamp) {
    if (this.passwordChangedAt) {

        const changedTimestamp = parseInt(this.passwordChangedAt.getTime() / 1000, 10)

        return JWTTimestamp < changedTimestamp
    }

    return false;
};

userSchema.methods.createPasswordResetToken = function () {
    const resetToken = crypto.randomBytes(32).toString('hex')

    this.passwordResetToken = crypto
        .createHash('sha256')
        .update(resetToken)
        .digest('hex');

    this.passwordResetExpires = Date.now() + 10 * 60 * 1000;

    return resetToken;
}

const User = mongoose.model('User', userSchema);

module.exports = User;

控制器中使用的功能

const crypto = require('crypto');
const {
    promisify
} = require('util');
const jwt = require('jsonwebtoken');
const User = require('./../models/userModel');
const catchAsync = require('./../utils/catchAsync');
const sendEmail = require('./../utils/email');

const AppError = require('../utils/appError');

const signToken = id => {
    return jwt.sign({
            id: id
        },
        process.env.JWT_SECRET, {
            expiresIn: process.env.JWT_EXPIRES_IN
        });
}

const createSendToken = (user, statusCode, res) => {
    const token = signToken(user._id);
    const cookieOptions = {
        expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
        httpOnly: true,
    }

    if (process.env.NODE_ENV === 'production') cookieOptions.secure = true;
    res.cookie('jwt', token, cookieOptions);

    // Remove password from output
    user.password = undefined;

    res.status(statusCode).json({
        status: 'success',
        token,
        data: {
            user
        }
    })
}

exports.signup = catchAsync(async (req, res, next) => {
    const newUser = await User.create({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        passwordConfirm: req.body.passwordConfirm,
        passwordChangedAt: req.body.passwordChangedAt,
        role: req.body.role,
    });

    createSendToken(newUser, 201, res);
});

exports.login = catchAsync(async (req, res, next) => {
    const {
        email,
        password
    } = req.body;

    // 1) Check if email and password exist
    if (!email || !password) {
        return new AppError('Please provide email and password', 400);
    }

    //2) Check if user exist and the password is correct
    const user = await User.findOne({
        email
    }).select('+password');

    if (!user || !(await user.correctPassword(password, user.password))) {
        return next(new AppError('Incorrect email or password', 401))
    }

    //3) if everything is ok send token to client
    createSendToken(user, 200, res);
});

我的依赖关系

"dependencies": {
    "@babel/polyfill": "^7.4.4",
    "axios": "^0.18.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "compression": "^1.7.4",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "dotenv": "^7.0.0",
    "express": "^4.16.4",
    "express-mongo-sanitize": "^1.3.2",
    "express-rate-limit": "^3.5.0",
    "helmet": "^3.16.0",
    "hpp": "^0.2.2",
    "html-to-text": "^5.1.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.3",
    "morgan": "^1.9.1",
    "multer": "^1.4.1",
    "nodemailer": "^6.1.1",
    "pug": "^2.0.3",
    "slugify": "^1.3.4",
    "stripe": "^7.0.0",
    "validator": "^10.11.0",
    "xss-clean": "^0.1.1"
  },
  "devDependencies": {
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-prettier": "^4.1.0",
    "eslint-plugin-import": "^2.17.2",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-node": "^8.0.1",
    "eslint-plugin-prettier": "^3.0.1",
    "eslint-plugin-react": "^7.12.4",
    "parcel-bundler": "^1.12.3",
    "prettier": "^1.17.0"
  },

正如您所看到的,我没有使用findbyid或任何需要mongoose检查objectid的东西,但它仍然说这是错误的。
在另一个浏览器中打开请求后看到的错误

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题