NodeJs/Express question

NodeJs/Express question


Can anyone explain why this code doesn’t work?"/api/exercise/new-user/", (req,res) => {
let username = req.body.username;

userDB.find({"user_name": {$eq: username}}, (err, doc) => {
if (doc) {
  return res.send('User already exists')
  console.log(username)//username doesn't get past the if statement 
                      //even if it isn't in the db
  let newUser = new userDB({
    user_name: username
  });, url) =>{
      user_name: username


Could you define “doesn’t work”? Do you get an error?


If the user isn’t in the database, it doesn’t get past the first part of the if statement. It returns “User already exists”. No error.


I’m pretty sure that doc will always be a truthy value, probably an empty object. Try console.log(doc) to confirm.


Maybe try findOne() instead. I think find() is returning a cursor, not a doc.


It was coming back as an empty object. findOne() works but bypassing creating a document in the collection. That’s ok though, I’m enjoying troubleshooting this.


Thank you, I really appreciate it.