Find if email exists using findOne [duplicate]CastError: Cast to ObjectId failed for value “route-name” at path “_id” for modelMongoDB - Cast to ObjectId failed for value “create” at path “_id”Check synchronously if file/directory exists in Node.jsFind the version of an installed npm packageHow to use deferrable to execute a sequence of Redis operations?Calling and Saving User Account Custom Dataexpress-ejs-layout sometimes fails to detect passing argumentUndefined _id populate with express, moongose/MongoDB on NodejsExpress req.body not WorkingTwo-Way-Authentication via Email in nodejsI got an empty array in sub document array saving using mongoose ( MEAN stack)Passport-local times out on create user (Node, Express, Postgres, Knex)

Multi tool use
Multi tool use

Why did it take so long for Germany to allow electric scooters / e-rollers on the roads?

What could be my risk mitigation strategies if my client wants to contract UAT?

Why is this integration method not valid?

If I arrive in the UK, and then head to mainland Europe, does my Schengen visa 90 day limit start when I arrived in the UK, or mainland Europe?

How did the Allies achieve air superiority on Sicily?

Seeking closure over someone I have unblocked but whom I learned have passed on

Is it normal to "extract a paper" from a master thesis?

Toxic, harassing lab environment

Did Game of Thrones end the way that George RR Martin intended?

Cisco 3750X Power Cable

How to create a `range`-like iterable object of floats?

To exponential digit growth and beyond!

Why isn't Tyrion mentioned in 'A song of Ice and Fire'?

How do you earn the reader's trust?

Is superuser the same as root?

Why was this character made Grand Maester?

ifconfig shows UP while ip link shows DOWN

Maximum interval between Alto & Tenor, & intervals when writing for SATB

Split into three!

Example of a ring where every module of finite projective dimension is free?

Possibility of faking someone's public key

Determine direction of mass transfer

Negative impact of having the launch pad away from the Equator

How does Dreadhorde Arcanist interact with split cards?



Find if email exists using findOne [duplicate]


CastError: Cast to ObjectId failed for value “route-name” at path “_id” for modelMongoDB - Cast to ObjectId failed for value “create” at path “_id”Check synchronously if file/directory exists in Node.jsFind the version of an installed npm packageHow to use deferrable to execute a sequence of Redis operations?Calling and Saving User Account Custom Dataexpress-ejs-layout sometimes fails to detect passing argumentUndefined _id populate with express, moongose/MongoDB on NodejsExpress req.body not WorkingTwo-Way-Authentication via Email in nodejsI got an empty array in sub document array saving using mongoose ( MEAN stack)Passport-local times out on create user (Node, Express, Postgres, Knex)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0
















This question already has an answer here:



  • MongoDB - Cast to ObjectId failed for value “create” at path “_id”

    2 answers



  • CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

    1 answer



I want to find if email exists in mongodb but when I send GET request using postman, I get error response.



Request:




"email":"myemail@gmail.com"



Response:




"message": "Cast to ObjectId failed for value "email" at path "_id" for model "User""



This is my users.controller.js:



router.get('/email', getByEmail); // defined route
...
function getByEmail(req, res, next)
userService.getByEmail(req.body)
.then(user => user ? res.json(user) : res.sendStatus(404))
.catch(err => next(err));



This is users.service.js:



async function getByEmail(email) 
const user = await User.findOne(email).select('-hash');
return user;



It makes no sense to me since in my other function, for example user login, I do the same to check if email exists, and it works. Here is the login:



Controller:



router.post('/authenticate', authenticate);
...
function authenticate(req, res, next)
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json( message: 'Email or password is incorrect' ))
.catch(err => next(err));



Servcice:



async function authenticate( email, password ) 
const user = await User.findOne( email );
if (user && bcrypt.compareSync(password, user.hash))
const hash, ...userWithoutHash = user.toObject();
const token = jwt.sign( sub: user.id , config.secret);
return
...userWithoutHash,
token
;




Edit:



I found out that when I change the request to POST and also change the function to return true or false if the object exists or not, it works, but how should I change it so it works for GET request?










share|improve this question















marked as duplicate by Neil Lunn mongodb
Users with the  mongodb badge can single-handedly close mongodb questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 23:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

    – Neil Lunn
    Mar 23 at 23:00











  • @NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

    – mrRobot
    Mar 23 at 23:18






  • 1





    The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

    – Neil Lunn
    Mar 23 at 23:24

















0
















This question already has an answer here:



  • MongoDB - Cast to ObjectId failed for value “create” at path “_id”

    2 answers



  • CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

    1 answer



I want to find if email exists in mongodb but when I send GET request using postman, I get error response.



Request:




"email":"myemail@gmail.com"



Response:




"message": "Cast to ObjectId failed for value "email" at path "_id" for model "User""



This is my users.controller.js:



router.get('/email', getByEmail); // defined route
...
function getByEmail(req, res, next)
userService.getByEmail(req.body)
.then(user => user ? res.json(user) : res.sendStatus(404))
.catch(err => next(err));



This is users.service.js:



async function getByEmail(email) 
const user = await User.findOne(email).select('-hash');
return user;



It makes no sense to me since in my other function, for example user login, I do the same to check if email exists, and it works. Here is the login:



Controller:



router.post('/authenticate', authenticate);
...
function authenticate(req, res, next)
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json( message: 'Email or password is incorrect' ))
.catch(err => next(err));



Servcice:



async function authenticate( email, password ) 
const user = await User.findOne( email );
if (user && bcrypt.compareSync(password, user.hash))
const hash, ...userWithoutHash = user.toObject();
const token = jwt.sign( sub: user.id , config.secret);
return
...userWithoutHash,
token
;




Edit:



I found out that when I change the request to POST and also change the function to return true or false if the object exists or not, it works, but how should I change it so it works for GET request?










share|improve this question















marked as duplicate by Neil Lunn mongodb
Users with the  mongodb badge can single-handedly close mongodb questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 23:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 1





    You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

    – Neil Lunn
    Mar 23 at 23:00











  • @NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

    – mrRobot
    Mar 23 at 23:18






  • 1





    The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

    – Neil Lunn
    Mar 23 at 23:24













0












0








0









This question already has an answer here:



  • MongoDB - Cast to ObjectId failed for value “create” at path “_id”

    2 answers



  • CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

    1 answer



I want to find if email exists in mongodb but when I send GET request using postman, I get error response.



Request:




"email":"myemail@gmail.com"



Response:




"message": "Cast to ObjectId failed for value "email" at path "_id" for model "User""



This is my users.controller.js:



router.get('/email', getByEmail); // defined route
...
function getByEmail(req, res, next)
userService.getByEmail(req.body)
.then(user => user ? res.json(user) : res.sendStatus(404))
.catch(err => next(err));



This is users.service.js:



async function getByEmail(email) 
const user = await User.findOne(email).select('-hash');
return user;



It makes no sense to me since in my other function, for example user login, I do the same to check if email exists, and it works. Here is the login:



Controller:



router.post('/authenticate', authenticate);
...
function authenticate(req, res, next)
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json( message: 'Email or password is incorrect' ))
.catch(err => next(err));



Servcice:



async function authenticate( email, password ) 
const user = await User.findOne( email );
if (user && bcrypt.compareSync(password, user.hash))
const hash, ...userWithoutHash = user.toObject();
const token = jwt.sign( sub: user.id , config.secret);
return
...userWithoutHash,
token
;




Edit:



I found out that when I change the request to POST and also change the function to return true or false if the object exists or not, it works, but how should I change it so it works for GET request?










share|improve this question

















This question already has an answer here:



  • MongoDB - Cast to ObjectId failed for value “create” at path “_id”

    2 answers



  • CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

    1 answer



I want to find if email exists in mongodb but when I send GET request using postman, I get error response.



Request:




"email":"myemail@gmail.com"



Response:




"message": "Cast to ObjectId failed for value "email" at path "_id" for model "User""



This is my users.controller.js:



router.get('/email', getByEmail); // defined route
...
function getByEmail(req, res, next)
userService.getByEmail(req.body)
.then(user => user ? res.json(user) : res.sendStatus(404))
.catch(err => next(err));



This is users.service.js:



async function getByEmail(email) 
const user = await User.findOne(email).select('-hash');
return user;



It makes no sense to me since in my other function, for example user login, I do the same to check if email exists, and it works. Here is the login:



Controller:



router.post('/authenticate', authenticate);
...
function authenticate(req, res, next)
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json( message: 'Email or password is incorrect' ))
.catch(err => next(err));



Servcice:



async function authenticate( email, password ) 
const user = await User.findOne( email );
if (user && bcrypt.compareSync(password, user.hash))
const hash, ...userWithoutHash = user.toObject();
const token = jwt.sign( sub: user.id , config.secret);
return
...userWithoutHash,
token
;




Edit:



I found out that when I change the request to POST and also change the function to return true or false if the object exists or not, it works, but how should I change it so it works for GET request?





This question already has an answer here:



  • MongoDB - Cast to ObjectId failed for value “create” at path “_id”

    2 answers



  • CastError: Cast to ObjectId failed for value “route-name” at path “_id” for model

    1 answer







node.js mongodb express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 22:31







mrRobot

















asked Mar 23 at 21:46









mrRobotmrRobot

405




405




marked as duplicate by Neil Lunn mongodb
Users with the  mongodb badge can single-handedly close mongodb questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 23:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Neil Lunn mongodb
Users with the  mongodb badge can single-handedly close mongodb questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 23 at 23:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 1





    You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

    – Neil Lunn
    Mar 23 at 23:00











  • @NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

    – mrRobot
    Mar 23 at 23:18






  • 1





    The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

    – Neil Lunn
    Mar 23 at 23:24












  • 1





    You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

    – Neil Lunn
    Mar 23 at 23:00











  • @NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

    – mrRobot
    Mar 23 at 23:18






  • 1





    The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

    – Neil Lunn
    Mar 23 at 23:24







1




1





You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

– Neil Lunn
Mar 23 at 23:00





You have other code in the route you are not showing. Odds are you have a "root" / route with an id or similar named parameter on it like /:id. Within that route you are calling findById, which is where the actual error is coming from. The problem is that /email is actually being sent to /:id because that is defined first in the code. That's why the string email get's sent to findById. Basically the /email route you show above needs to be defined before the /:id route so that will be matched first.

– Neil Lunn
Mar 23 at 23:00













@NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

– mrRobot
Mar 23 at 23:18





@NeilLunn ahhhhh, what?! You are absolutely right, but could you explain it why is it like that? I haven't tried to change it yet, but I can see that everything you said is as I have it implemented.

– mrRobot
Mar 23 at 23:18




1




1





The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

– Neil Lunn
Mar 23 at 23:24





The linked answers show example changes of how an why you order routes when defining them. Please read those for details.

– Neil Lunn
Mar 23 at 23:24












0






active

oldest

votes

















0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes

u8,dL2 c5ouT
PW Tej 4HlGM,Tu i8xqdDK070Hr U,4NPAo8I ue50oFT DWlCLX7 X5R vmwxInTBHksu2 Z

Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

위키백과:대문 둘러보기 메뉴기부 안내모바일판 대문크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0CebuanoDeutschEnglishEspañolFrançaisItaliano日本語NederlandsPolskiPortuguêsРусскийSvenskaTiếng ViệtWinaray中文العربيةCatalàفارسیSrpskiУкраїнськаБългарскиНохчийнČeštinaDanskEsperantoEuskaraSuomiעבריתMagyarՀայերենBahasa IndonesiaҚазақшаBaso MinangkabauBahasa MelayuBân-lâm-gúNorskRomânăSrpskohrvatskiSlovenčinaTürkçe