简体   繁体   中英

Node.js issue with schema. user ID validation error

I am quite new to node.js express. I am having an issue with my registration form, I used a condition which checks my user id is already in the database or not. it used to work before. now no matter what different userID i give, it always shows me validation error messge. here is my controller code.

exports.registerTeacher=(req, res) => {
 
   let userIDTaken = User.findOne(req.body.userid); //here i am searching for userID in collection
   if (userIDTaken) { //my condition about if userID exists in collection
     return res.status(400).json({
       message: `userID is already taken.`, //showing the message
       success: false
     });
   }
   let emailTaken = User.findOne(req.body.email); //same condition for email
   if (emailTaken) {
     return res.status(400).json({
       message: `email is already taken.`,
       success: false
     });
   }
 
 if (!req.files || Object.keys(req.files).length === 0) {
   return res.status(400).send('No files were uploaded.');
 }
 let profileImage = req.files.profileImage;

 let uploadPath= `public/profile/${req.body.userid}.jpg`;
 
 profileImage.mv( uploadPath, function(err) {
   if (err)
     return res.status(500).send(err);

   res.send('File uploaded!');
 });

 const password =  bcrypt.hashSync(req.body.userid, 12);

 const product = new User({
   name: req.body.name,
   email: req.body.email,
   role: "teacher",
   userid:req.body.userid,
   password:password,
   profileImage: uploadPath
 });
 product
   .save()
   .then(result => {
     //console.log(result);
     res.status(201).json({
       message: "Created Profile successfully",
     });
   })
   .catch(err => {
     console.log(err);
     res.status(500).json({
       error: err
     });
   });
 }

this piece of code used to work 2 days back, I havent done anything with my db, I have deleted all the collections. And I havent change anything related to db. what should I do? and what did i do wrong

here is the console log of req.body.userid and userIDTaken inside the condition.


45451212
Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection:
   NativeCollection {
     collection: Collection { s: [Object] },
     Promise: [Function: Promise],
     opts:
      { bufferCommands: true,
        capped: false,
        Promise: [Function: Promise],
        '$wasForceClosed': undefined },
     name: 'users',
     collectionName: 'users',
     conn:
      NativeConnection {
        base: [Mongoose],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        options: null,
        otherDbs: [],
        relatedDbs: {},
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        plugins: [],
        _listening: false,
        _connectionOptions: [Object],
        name: 'student-portal',
        host: 'localhost',
        port: 27017,
        user: undefined,
        pass: undefined,
        client: [MongoClient],
        '$initialConnection': [Promise],
        db: [Db] },
     queue: [],
     buffer: false,
     emitter:
      EventEmitter { _events: {}, _eventsCount: 0, _maxListeners: undefined } },
  model: Model { users },
  schema:
   Schema {
     obj:
      { name: [Object],
        email: [Object],
        role: [Object],
        userid: [Object],
        password: [Object],
        profileImage: [Object] },
     paths:
      { name: [SchemaString],
        email: [SchemaString],
        role: [SchemaString],
        userid: [SchemaString],
        password: [SchemaString],
        profileImage: [SchemaString],
        _id: [ObjectId],
        updatedAt: [SchemaDate],
        createdAt: [SchemaDate],
        __v: [SchemaNumber] },
     aliases: {},
     subpaths: {},
     virtuals: { id: [VirtualType] },
     singleNestedPaths: {},
     nested: {},
     inherits: {},
     callQueue: [],
     _indexes: [],
     methods: { initializeTimestamps: [Function] },
     methodOptions: {},
     statics: {},
     tree:
      { name: [Object],
        email: [Object],
        role: [Object],
        userid: [Object],
        password: [Object],
        profileImage: [Object],
        _id: [Object],
        updatedAt: [Function: Date],
        createdAt: [Function: Date],
        __v: [Function: Number],
        id: [VirtualType] },
     query: {},
     childSchemas: [],
     plugins: [ [Object], [Object], [Object], [Object], [Object] ],
     '$id': 1,
     s: { hooks: [Kareem] },
     _userProvidedOptions: { timestamps: true },
     options:
      { timestamps: true,
        typePojoToMixed: true,
        typeKey: 'type',
        id: true,
        noVirtualId: false,
        _id: true,
        noId: false,
        validateBeforeSave: true,
        read: null,
        shardKey: null,
        autoIndex: null,
        minimize: true,
        discriminatorKey: '__t',
        versionKey: '__v',
        capped: false,
        bufferCommands: true,
        strict: true,
        pluralization: true },
     '$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
     '$globalPluginsApplied': true },
  op: 'findOne',
  options: {},
  _conditions: { userid: '45451212' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection:
   NodeCollection {
     collection:
      NativeCollection {
        collection: [Collection],
        Promise: [Function: Promise],
        opts: [Object],
        name: 'users',
        collectionName: 'users',
        conn: [NativeConnection],
        queue: [],
        buffer: false,
        emitter: [EventEmitter] },
     collectionName: 'users' },
  _traceFunction: undefined,
  '$useProjection': true }

even when i command db.getCollection('users').find({userid: 45451212}) in my db command. it shows zero record, so it clearly isnt in the database.

my User Schema


const { Schema, model } = require("mongoose");

const UserSchema = new Schema(
  {
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    role: {
      type: String,
      default: "student",
      enum: ["student", "teacher", "parent","admin"]
    },
    userid: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    
    profileImage: { 
      type: String, 
      required: false
    }
  },
  { timestamps: true }
);

module.exports = model("users", UserSchema);

maybe you can rewrite your code using callbacks, eg:

User.findOne(req.body.userid, function(err,resp){

if(resp){

return res.status(400).json({
       message: `email is already taken.`,
       success: false}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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