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
could you please replace your code-
With my code and lemme know the result-
This may works only with email.. but first lemme know the result.. i will help you more..
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.