NodeJs/Express question

NodeJs/Express question
0.0 0

#1

Can anyone explain why this code doesn’t work?

app.post("/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')
}
else{
  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
  });
  newUser.save((err, url) =>{
    res.json({
      user_name: username
    })
  });
}
});
});

#2

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


#3

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.


#4

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


#5

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


#6

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.


#7

Thank you, I really appreciate it.