简体   繁体   English

FindOne 无法正确比较字符串 Express 和 MongoDB

[英]FindOne does not correctly compare string Express and MongoDB

I am doing a Role validation with the database using Express, express-validator and MongoDB to create a new user checking that the User Role exists in the Database.我正在使用 Express、express-validator 和 MongoDB 对数据库进行角色验证,以创建一个新用户,检查数据库中是否存在用户角色。

In my route using express-validator I verify that the Role exists using findOne to be able to post a new user but even if the role is correct it always tells me that the role does not exist.在我使用 express-validator 的路线中,我使用 findOne 验证角色是否存在以便能够发布新用户,但即使角色正确,它也总是告诉我该角色不存在。

Route:路线:

import Role from '../models/role';
import { check } from 'express-validator';


  router.post('/', 
   [
   check('role').custom( async (role = '') => {

            let roleExists = await Role.findOne( { role } );

            if ( !roleExists ) {
                throw new Error('El Rol no es válido');
            }
            
          }  ,
        ), 


    ], newUser);

Role Model角色 Model


import { Schema, model } from "mongoose";

const RoleSchema = Schema (
  {
    role: {
        type: String,
        required: [true, 'El Rol es obligatorio']
    }
  }  
);

module.exports = model('Role', RoleSchema);

Attached Document in MongoDB, request with postman and postman response. MongoDB 中的附件,请求与 postman 和 postman 响应。

MongoDB文档

邮递员回应

debugger roleExists is exist, no roleExist throw error调试器 roleExists 存在,没有 roleExist 抛出错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM