w13rfed
w13rfed

Reputation: 375

Unhandled Promise Rejection Warning Cast error

I'm stuck with an error using mongoose and mongodb that won't let me locate things in my database beause of cast errors.

I have a user schema

const schema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, min: 1, required: true }
});

export default mongoose.model('user',schema);

in another file I have this where the user_id gets input from an input field

User.findOne({ name: user_id })
  .then(user => {
    if(user) {
      console.log("found user");
      console.log(user);
    } else {
      console.log("user not found");
    }
  })
});

The problem is that I get the cast error, also in the error I can see the value of user_id is getting the correct value, i.e 'testing', name of user in database i'm inputting from input field.

(node:1127) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): CastError: Cast to string failed for value "{ user_id: 'testing' }" at path "name" for model "user"

If I change the first line of code to

User.findOne({})

The query finds one and prints out

{ _id: 5a952b07327915e625aa0fee, name: 'testing' }

but if I change the code to either

User.findOne({ name: user_id })

and enter in the search box 'testing', or

User.findOne({ _id: user_id })

and then enter in the id '5a952b07327915e625aa0fee', I get the error. I also get a similar error when using

User.findById(user_id)
node:1166) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): CastError: Cast to ObjectId failed for value "{ user_id: '5a952adf327915e625aa0fed' }" at path "_id" for model "user"

Thanks

Upvotes: 0

Views: 2029

Answers (2)

Csaba
Csaba

Reputation: 419

Try the following:

User.findById('5a952adf327915e625aa0fed')
    .then(user => console.log(user))  // user can be undefined
    .catch(e => console.error(e))

or

User.findOne({name: 'testing'})
    .then(user => console.log(user))  // user can be undefined
    .catch(e => console.error(e))

Upvotes: 2

Rahul Sharma
Rahul Sharma

Reputation: 10081

Try this

User.findOne({ name: user_id })
  .then(user => {
    if(user) {
      console.log("found user");
      console.log(user);
    } else {
      console.log("user not found");
    }
}).catch(err => console.log("something went wrong");)

Upvotes: 1

Related Questions