sharad chauhan sharad chauhan - 1 year ago 65
Javascript Question

Unable to use mongoose model

I am doing simple registration using mongoose. I have take a javascript file in which i am storing the values of registration form.

Here is my registrationButtonAction.js

window.onload = function() {

var User = require('/models/Mongoose Database/user_database');
// this line is causing the problem

var registerButton = document.getElementById("registerMe");
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var usernameRegister = document.getElementById("usernameRegister");
var passwordRegister = document.getElementById("passwordRegister");
var repasswordRegister = document.getElementById("repasswordRegister");

registerButton.onclick = function () {

if(!firstName.value || !passwordRegister.value || !repasswordRegister.value || !usernameRegister.value){
alert("Enter all required fields");
}else if (passwordRegister.value != repasswordRegister.value){
alert("Passwords must match");
}else {
var newUser = new User({
username : usernameRegister.value,
password : passwordRegister.value
User.find({username:usernameRegister.value}, function (error, user) {

if (error) throw error;

}else { (error) {
if(error) throw error;
// user.comparePassword(passwordRegister.value, function (error, isMatch) {
// if (error) throw error;
// return 1;





When i comment the var
User = require('/models/Mongoose Database/user_database');
all the checks are working fine inside onclick function. But when i uncomment it, it is not recognizing the button click. I want to know whether it is a correct way of taking values from registration page and storing them in mongoose database. Please provide some guidance for the same. And to point out i am designing my page in EJS and not in Jade. Thanks.

Answer Source

You are mixing server and client code. Mongoose models and Node.js functions are not accessible inside window.onload on your client.

To put it simply, you need to create a REST API to perform database operations on the server. You have all the right tools aready, just need to reorder them.

The flow would be as such :

  • get the values entered in the browser
  • call an endpoint on your server (for example /api/createUser)
  • in the express router, have a route called /api/createUser in which you can access your User model and perform creation/deletion/update, etc.

My suggestion would be for you to go through this tutorial which should remove your confusion and bring you up to speed in no time. Good Luck!

Also, Passport can help you with authentication, but I believe you should first learn how to build a basic API. Authentication is a tricky beast ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download