# How do I call a function in Node.js?

**URL:** <https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904>\
**Category:** Curriculum Help\
**Tags:** javascript\
**Created:** [December 15, 2018, 7:53pm UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904 "2018-12-15T19:53:30Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![adam-weiler](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/adam-weiler/32/106955_2.png) [@adam-weiler](https://forum.freecodecamp.org/u/adam-weiler)\
**Post date:** [December 15, 2018, 7:53pm UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/1 "2018-12-15T19:53:30Z")

</div>

I’m working on the Exercise Tracker API, and I’m at the part where the user submits their username.

I’ve got the user\_name from the post, I’ve got a var function that checks the database for the username, but I don’t know how to call it and assign the true/false to a variable.

This is what I’ve got sofar:

```auto
//Get user_name from post.
app.post("/api/exercise/new-user", function (req, res) {
  let user_name = req.body.username; //Gets the URL from the body of the page.

  var checking = exports.findPeopleByName = findPeopleByName; //This part is wrong.
  
  res.json({"username":user_name, "does he exist?":checking});
});

//Check the database if user exists.
var findPeopleByName = function(userName, done) {
  User.find({username:userName}, (err, data) => {
      if(err) {
         done(err); 
      }
    done(null, data);
    }) 
};

```

I looked through the lessons and I can’t seem to find how to call the var functions. I tried using the exports but I feel that’s not right.

---

<div class="post-metadata">

**Author:** ![Layer](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/layer/32/82898_2.png) [@Layer](https://forum.freecodecamp.org/u/Layer)\
**Post date:** [December 16, 2018, 7:02am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/2 "2018-12-16T07:02:43Z")

</div>

Sometimes we overthink the problems: that’s just plain javascript 😄

```auto
app.post("/api/exercise/new-user", function (req, res) {
  let user_name = req.body.username; //Gets the URL from the body of the page.

  findPeopleByName(user_name, function(err, data) {
        if(err){
                res.json(err);
         }
         res.json({"username":user_name});
       });
});

```

You could use some more actual code but the above should be easier to compare with the snippet you provided^^

---

<div class="post-metadata">

**Author:** ![adam-weiler](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/adam-weiler/32/106955_2.png) [@adam-weiler](https://forum.freecodecamp.org/u/adam-weiler)\
**Post date:** [December 17, 2018, 3:02am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/3 "2018-12-17T03:02:18Z")

</div>

It doesn’t seem to be working. I removed the function outside the app.post, and put in the code you suggested.

-At first the server is giving me a pink error `findPeopleByName is not defined`.  
-So I tried to define it as a var and then it says `Parsing error: unexpeked token (`  
-I tried removing each bracket individually and that doesn’t seem to help.  
-If I define `var findPeopleByName` above, and then use the code you suggested then the server tests pass.

But then when I run the app itself, it’s returning `findPeopleByName is not a function`. So that means I need to declare it as a function?

_I think I need to go back and reread the JavaScript unit… 😅_

**EDIT:** I’m not sure if this is the correct way to do things, but this seems to pass the server tests and works on the app itself:

```auto
  var findPeopleByName;
  
  findPeopleByName(user_name, function(err, data) {
        if(err){
                res.json(err);
         }
         res.json({"username":user_name});
       }());
});

```

Basically it’s the same that you wrong, only with the `var` statement on a separate line, and the `()` brackets near the bottom.

---

<div class="post-metadata">

**Author:** ![kevinSmith](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/kevinsmith/32/72934_2.png) [@kevinSmith](https://forum.freecodecamp.org/u/kevinSmith)\
**Post date:** [December 17, 2018, 3:16am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/4 "2018-12-17T03:16:52Z")

</div>

Can you post all of the code? Layer’s solution is solid. This is just JS so it’s just like creating and calling functions on the front end.

Your `findPeopleByName is not defined` error is because of the way your function declaration is hoisted.

```auto
var findPeopleByName = function(userName, done) {

```

The variable declaration is hoisted but its value is undefined until the parser reaches it, so when it is called it is undefined. Just define it like:

```auto
function findPeopleByName(userName, done) {

```

---

<div class="post-metadata">

**Author:** ![willjw3](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/willjw3/32/196790_2.png) [@willjw3](https://forum.freecodecamp.org/u/willjw3)\
**Post date:** [December 17, 2018, 3:17am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/5 "2018-12-17T03:17:42Z")

</div>

Didn’t you say you were checking the database for the user name? Specifically:

```auto
var findPeopleByName = function(userName, done) {
  User.find({username:userName}, (err, data) => {
      if(err) {
         done(err); 
      }
    done(null, data);
    }) 
};

```

If you use the `find()` method of mongoDB, a cursor that points to the result set of a query is returned. If you use `find().toArray()`, what’s returned is an array of documents that match your query. If you just want to return one document, use the `findOne()` method.

**(Late addition)**: However, this is when interacting with MongoDB without any help; if you’re using Mongoose, things will be different.

[https://docs.mongodb.com/manual/reference/method/db.collection.find/](https://docs.mongodb.com/manual/reference/method/db.collection.find/)  
[https://docs.mongodb.com/manual/reference/method/db.collection.findOne/](https://docs.mongodb.com/manual/reference/method/db.collection.findOne/)

---

<div class="post-metadata">

**Author:** ![adam-weiler](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/adam-weiler/32/106955_2.png) [@adam-weiler](https://forum.freecodecamp.org/u/adam-weiler)\
**Post date:** [December 17, 2018, 5:06am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/6 "2018-12-17T05:06:47Z")

</div>

```auto
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

const cors = require('cors')

const mongoose = require('mongoose')
mongoose.connect(process.env.MONGO_URI)
.then(
  () => {
    console.log("mongo opened:", process.env.MONGO_URI)    
  },
  err => {
    console.error("### error starting mongo:", process.env.MONGO_URI)
    console.error(err)
  }
)

app.use(cors())

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

//Creates a URL model or Schema.
const userSchema = new mongoose.Schema({
  _id: Number,
  username: { type: String, required: true },
  log:[{
    description: { type: String, required: true },
    duration: { type: String, required: true },
    date: { type: String },
  }]
});

var User = mongoose.model('User', userSchema);

app.post("/api/exercise/new-user", function (req, res) {
  let user_name = req.body.username; //Gets the URL from the body of the page.
    
  if (!user_name) {
    res.json('Path `username` is required.'); 
  }
  
  var findPeopleByName = function(user_name, done) {
    User.find({username:user_name}, (err, data) => {
        if(err) {
           done(err); 
        }
      done(null, data);
      }) 
  };
});

// Not found middleware
app.use((req, res, next) => {
  return next({status: 404, message: 'not found'})
})

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage

  if (err.errors) {
    // mongoose validation error
    errCode = 400 // bad request
    const keys = Object.keys(err.errors)
    // report the first validation error
    errMessage = err.errors[keys[0]].message
  } else {
    // generic or custom error
    errCode = err.status || 500
    errMessage = err.message || 'Internal Server Error'
  }
  res.status(errCode).type('txt')
    .send(errMessage)
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

```

I’ve added a user called `"username": "Adam"` to the database, but when I try to test it I’m getting `502 Bad Gateway`.

Also in the logs it says `://(username):(password)@(numbers).mlab.com:(numbers)/exercise_tracker_database`, which should mean it’s connected to the database.

This is the app at the moment with the above code:  
[https://dog-comic.glitch.me/](https://dog-comic.glitch.me/)

---

<div class="post-metadata">

**Author:** ![kevinSmith](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/kevinsmith/32/72934_2.png) [@kevinSmith](https://forum.freecodecamp.org/u/kevinSmith)\
**Post date:** [December 17, 2018, 5:26am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/7 "2018-12-17T05:26:00Z")

</div>

I meant the route code. With will’s function call and my changing how the function is defined (or by moving it to the top of the file), that should fix it.

---

<div class="post-metadata">

**Author:** ![Layer](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/layer/32/82898_2.png) [@Layer](https://forum.freecodecamp.org/u/Layer)\
**Post date:** [December 17, 2018, 6:55am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/8 "2018-12-17T06:55:47Z")

</div>

> It doesn’t seem to be working. **I removed the function outside the app.post** , and put in the code you suggested

The snippet i suggested is meant to replace what’s inside the `app.post` method, the stuff outside was fine ^^

> this seems to pass the server tests and works on the app itself:

`Works` means that pass the test right? Because that function does not connect to the database to find something (`User.find(...` is the code actually searching in the db)

Nvm, @kevinSmith and @willjw3 have given you valuable info, let us know if it is enough to solve the issue 🤞

---

<div class="post-metadata">

**Author:** ![adam-weiler](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/adam-weiler/32/106955_2.png) [@adam-weiler](https://forum.freecodecamp.org/u/adam-weiler)\
**Post date:** [December 17, 2018, 7:31pm UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/10 "2018-12-17T19:31:00Z")

</div>

OH, okay! I was confused, I thought the snippet was a replacement, not an addition!

This code seems to be working now, I can check if the user exists, add new users, and it stops users with the same name:

[https://dog-comic.glitch.me/](https://dog-comic.glitch.me/)  
[https://dog-comic.glitch.me/api/exercise/users](https://dog-comic.glitch.me/api/exercise/users)

```auto
app.post("/api/exercise/new-user", function(req, res) {
	let user_name = req.body.username; //Gets the user_name from the body of the page.

	if (!user_name) { //User input is blank.
		res.json('Path `username` is required.');
	}

	findUserByName(user_name, function(err, data) { //Checks if user input is in database already.
		if (err) {
			res.json(err);
		}

		if (data != null) { //If not null then user input is in database already.
			res.json('Username already taken.');
		} else { //Else null then user input is new.
			
			createAndSaveUser(user_name, function(err, data) { //Creates and saves new person to database.
				if (err) {
					res.json(err);
				}
				res.json({ "username": user_name, "_id": data });
			});
		}
	});
});

var findUserByName = function(userName, done) { //Check the database if User exists.
	User.findOne({ username: userName }, (err, data) => {
		if (err) {
			done(err);
		}
		done(null, data);
	})
};

var createAndSaveUser = function(userName, done) { //Adds a new User.
	var randomID = makeid();

	var newUser = new User({ _id: randomID, username: userName });

	newUser.save(function(err, data) {
		if (err) return done(err)
		return done(null, randomID);
	});
}

function makeid() {
	var text = "";
	var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	for (var i = 0; i < 9; i++)
		text += possible.charAt(Math.floor(Math.random() * possible.length));

	return text;
}

```

Thank you so much everyone! I think I have a better grasp of what I’m doing now! 😁

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 17, 2021, 7:30am UTC](https://forum.freecodecamp.org/t/how-do-i-call-a-function-in-node-js/245904/11 "2021-01-17T07:30:07Z")

</div>

Closed on January 17, 2021, 7:30am UTC


