skip to Main Content
const express = require('express');
const app = express();
const Register = require('./model/register')
require('./db/conection');
app.use(express.json());

app.get('/' , async(req,res)=>{
    res.send("hello")
    
})
app.get('/search/:key',async(req,res)=>{
    let sKey=req.params.key;
    console.log(typeof(sKey));
    let searchData=await Register.findOne({'$or':[
        {name:sKey},
        {email:sKey},
        {address:sKey},
        {mobile:sKey}
    ]})
    res.send(searchData);
})
app.listen(5000,()=>{
    console.log("server start");
    console.log(`http://localhost:5000`)

});

I am triying to create searching api for getting detail of a particular user by email or mobile number and my code shows this error :UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "[email protected]" (type string) at path "mobile" for model "users".

my model file is –

const mongoose = require('mongoose')
//const {Schema} = mongoose
const registerSchema = new mongoose.Schema ({
name:String,
email:String,
address:String,
mobile:Number,
password:String,
date:{type:Date , default:Date.now}
});
const Register = mongoose.model('users',registerSchema);
module.exports= Register;

2

Answers


  1. could you please replace your code-

    let searchData=await Register.findOne({'$or':[
            {name:sKey},
            {email:sKey},
            {address:sKey},
            {mobile:sKey}
        ]})
    

    With my code and lemme know the result-

    let searchData= await Register.find({email:{$regex:sKey, $options:'i'}})
    

    This may works only with email.. but first lemme know the result.. i will help you more..

    Login or Signup to reply.
  2. In registerSchema, you have defined the mobile field as Number. So you have to make it a string or detect if the search value is a string or number.
    If the value is a number then you can add a custom where condition as given below.

    let whereCondition = [
        {name:sKey},
        {email:sKey},
        {address:sKey}
    ];
    
    if(typeof sKey == 'number'){
       whereCondition.push({mobile:sKey});
    }
    
    let searchData=await Register.findOne({'$or':[
        whereCondition
    ]});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search