What would findOne() in mongoDB return if the record does not exists? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

What would findOne() in mongoDB return if the record does not exists?

I am making a signUp service. my function at backend should return an error if email already exists in the database. Here is my function at the backend to handle my post method before posting I am checking if the user with the same emailId exits or not. At line 5, I am checking if some user exits with the emailId entered in the form(sent as a request to the function). The MongoDB documentation says findOne() will return a cursor when it finds a record for the query provided in the argument. I want to know what it returns when it could not able to find the record for the provided query. Please provide a way around. I am adding the code snippet: Have a look at the code here for a better view: https://codeshare.io/ld ________ router.post('/newuser', (req,res) =>{ let user = req.body; var query = {"email" : user.email}; let exist = Users.findOne(query); if(exist){ console.log('User exists'); } else{ console.log("null"); } res.set({ 'Content-Type' : 'application/json', 'Access-Control-Allow-Origin' : 'http://localhost:4200' }) if(exist){ res.json({message: "Already Exists"}) res.send(); } else{ //create user Users.create(user, function(err, succ){ if(err){ console.log("The error is:" + err); res.status(400); res.send(err); } else{ console.log("User created is:" + succ); res.send(succ); } }); } });

20th May 2018, 3:21 PM
Ashutosh
Ashutosh - avatar
1 Réponse
+ 4
findOne is asynchronous. To determine existence of user, check for callback argument, result. If null, user is not found. Users.findOne( query, function (err, result) { if (err) { ... } if (!result) { // do stuff here console.log('No found user); } // User found }
13th Mar 2020, 2:32 PM
Calviղ
Calviղ - avatar