How do I call a function in Node.js?

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:

//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.

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

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^^

1 Like

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… :sweat_smile:

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:

  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.

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.

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:

function findPeopleByName(userName, done) {
1 Like

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

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.findOne/

1 Like
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/

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.

1 Like

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 :crossed_fingers:

1 Like

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/api/exercise/users

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! :grin:

1 Like