Search code examples
node.jsmongoosemongoose-schema

mongoose isn't finding the value


why does this always return invalid creds when the password is correct? ‎‎‎Thank you!‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎

const schema = mongoose.Schema({
    pass: {
      type: String,
      required: true,
    }
  })
const password = mongoose.model('pass', schema)

mongo().then(async (mongoose) => {
  const test = new password({
    password: 'pass'
  })
  password.findOne({ password: passwordInput }, function (err, user) {
    if (err) {
      console.log(err);
    }
    else if (user) {
      log('LOGGED IN!')
    }
    else {
      log('Invalid creds');
    }
  });
})

Solution

  • A few issues with your code

    const schema = mongoose.Schema({
        pass: { // <---- property name is pass not password
          type: String,
          required: true,
        }
    })
    

    then here

    const test = new password({
        password: 'pass' // property name password not pass
    })
    

    also the above code does not save the password to db. You need to call save()

    const test = new password({
        password: 'pass' // property name password not pass
    })
    test.save();
    

    even like this it won't work because the save method is assynchronous which means it takes some time for it to get to db. So you would need to do something like this

    const test = new password({
        password: 'pass'
    })
    test.save(function(){
        // this function is called after the password was saved to db
        // now you can query db
        password.findOne({ pass.....
    });
    

    Complete code

    const schema = mongoose.Schema({
        password: {
            type: String,
            required: true,
        }
    })
    const password = mongoose.model('password', schema)
    
    mongo().then(async (mongoose) => {
        const test = new password({
            password: 'pass'
        })
        test.save(function(){
            password.findOne({ password: passwordInput }, function (err, user) {
                if (err) {
                    console.log(err);
                } else if (user) {
                    log('LOGGED IN!')
                }  else {
                    log('Invalid creds');
                }
            });
        });
    })