I am very new to nodejs and am not able to figure out what exactly is going on here-
i have a basic login page, in which as the user types in the values, i go to the home page, before which i check up on the database if that username exists or not. The problem i am having is that when i click on the submit button, the code never seems to reach the database function.
This is my module in app.js -
app.post('/home',function(req,res){
//check for user existence....
var str;
console.log("in home");
user_login.perform_login(req.body.username,function(err,str){
if(!err){
console.log(str+" in login");
var cookie_val=req.body.username;
res.cookie('username',cookie_val,{signed: true});
req.session.username=cookie_val;
res.render('home.ejs',{
layout: false,
locals: {varname: cookie_val},
udata: req.session.username
});
}
else{
console.log("Couldn't find it.");
res.redirect("/login");
}
});
});
This is the perform_login from user_login.js-
var mongo_db=require("./testdb.js");
exports.perform_login=function (username,callback){
mongo_db.getInfo(username,function(err,bundle){
if(!err){
//console.log("success\n"+bundle);
callback(false,bundle);
}
else{
//console.log("couldn't find it");
callback(true,null);
}
});
}
and this is the testdb.js-
var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/test');
exports.getInfo=function(value,callback){
var db=mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));
db.once('open',function(){
console.log("Connected!");
var userSchema=mongoose.Schema({
username: String,
password: String
});
var userInstances=mongoose.model('userInstances',userSchema);
userInstances.findOne({username: value},'username password',function(err,ui){
if(!err){
callback(false,ui);
}
else{
callback(true,"error");
}
});//findone
});//db.once function
}//getinfo
In the terminal i only get -"in home", after which nothing happens at all.In the browser, it seems to be processing but remains in the login page.
when i run the perform_login with an actual hard-coded value instead of req.body.username, immediately as app.js is launched, i get the proper results. So i am able to access the database somehow outside app.post().
Is there something wrong in the callbacks??
I think that you are doing a bit too much here. The symptoms you are describing are in my experience from a not connected mongoose. You do not need to manage the connection and listen on events, if it is connected. Mongoose handles this for you. You can query a model and it will return the result as soon the connection is established.
Here is an example that should work:
app.js
//initialize mongo connection
var mongooseConnection = mongoose.connect("mongodb://localhost/test");
user.js
var mongoose = require('mongoose');
var userSchema=mongoose.Schema({
username: String,
password: String
});
userSchema.statics.performLogin = function(username, callback) {
this.findOne({username: value},'username password',function(err,user){
if(!err){
callback(false,user);
}
else{
callback(true,"error");
}
});
module.exports = mongoose.model('users',userSchema);
route:
var User = require("./user");
app.post('/home',function(req,res){
User.performLogin(req.body.username, function (err, user) {
...
});
});
Related
I'm using React Admin for the first time, and my users (coming from mongoDB) are displayed just fine. The problem occurs when I click the "edit" (or "delete") button on a specific user: it says "GET http://localhost:3002/api/users/2a1a3a61-f73b-4a01-b609-ae4bb815f59e 404 (Not Found)"
I use "http://localhost:3002/api/users" to make the GET req to mongoDB: "app.use('/api/users', require('./api/GetUsers'))" and "2a1a3a61-f73b-4a01-b609-ae4bb815f59e" is the id of the user I clicked.
I remember when I first started testing React Admin, that I was using jsonplaceholder.typicode to get data and the edit function was working as well, although, of course, would not persist on refresh.
What am I missing? Is the problem the fact that my api's (http://localhost:3002/api/users) purpose is only getting the data and not post/put also, maybe?
/api/GetUsers
const express = require('express');
const mongoose = require('mongoose');
const ContactUser = require('../DB/ContactUser');
const router = express.Router();
const getUsers = async (req, res) => {
ContactUser.find()
.exec((err, user) => {
if(err){
res.json(err);
} else {
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'users 0-20/20');
res.json(user);
}
})
};
router.route('/').get(getUsers);
module.exports = router;
/DB/ContactUser
const mongoose = require('mongoose');
const contactUser = new mongoose.Schema({
name: String,
email: String,
message: String,
id: String
});
module.exports = mongoose.model('contactUser', contactUser);
You're missing a second route to retrieve not a list of users, but a single user. It will use the id in the URL to find one user. Something like:
router.get('/:id', function(req, res) {
ContactUser
.findOne({ _id: req.params.id })
.exec((err, user) => err ? res.json(err) : res.json(user));
});
In the example I am working with is this code:
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/my_database_name';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
//Create some users
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};
// Insert some users
collection.insert([user1, user2, user3], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
//Close connection
db.close();
});
}
});
As you may see, he is doing an operation in the connect function. I would like to keep it modular and separate the connection from DB operations.
My suggestion would be to make a singleton on db variable and reuse that one. At least that's what I would do in Java to which I am used to.
However, I am not sure as in the example he hasn't suggested anything like that.
I would recommend against maintaining one connection if you want any kind of scalability.
There are a number of options for connection pooling, etc, but most folks who spend any time at all with Node and MongoDB end up moving to Mongoose at some point.
In addition to adding a nice schema layer, it offers connection abstraction so that you can default to a shared connection by calling mongoose.connect(), or you can create multiple connections or participate in connection pooling by calling mongoose.createConnection(). In both cases, you call it without a callback, and the mongoose machinery will defer subsequent calls to the module until after the connection is established, so that your code doesn't have to care.
Something like your use case might look like so:
// in your app.js or server.js file
var mongoose = require('mongoose');
mongoose.connect(config.db.url); // assuming you have some module that handles config variables
Then in ./models/user.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number,
roles: [String]
});
mongoose.model('User',UserSchema);
finally, in lets say a seed function to create your initial batch of users:
const mongoose = require('mongoose'),
User = mongoose.model('User');
// create some users
var user1 = new User({name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']});
var user2 = new User({name: 'modulus user', age: 22, roles: ['user']});
user1.save(console.log);
user2.save(console.log);
I believe maintaining a single connection is the best as mentioned in another thread:
The primary comitter in node-mongodb-native says
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool. So open it once an[d] reuse across all requests.
Say on server start initiate the mongo connection.
Server.js:
...
var db = require('./db');//require db.js
db.openMongoConnection(function(error)
{
if(error)
{
console.log(error);
console.log("cannot make the connection with database");
}
else
{
server.listen(7400);//say ur server listening on 7000 port
}
}
db.js
var db1;
var MongoClient = require('mongodb').MongoClient;
exports.openMongoConnection = function(callback)
{
MongoClient.connect(<YourUrl1>,function(err,dbInstance)
{
if(err)
{
callback(err);
}
else
{
db1 = dbInstance;
callback(null);
}
});
};
exports.getCollection = function(collectionName, callback){
dbInstance.collection(collectionName, function(err, collectionInstance){
if(err)
{
callback(err);
}
else
{
callback(null, collectionInstance)
}
});
}
Then you can call the getCollection to use at anytime by requiring dbInsance
here is my complete code
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
webToken = require('jsonwebtoken'),
bcrypt = require('bcryptjs'),
assert = require('assert');
Schema = mongoose.Schema,
secretKey = "omjdiuwkslxmshsoepdukslsj";
//User Schema
var userSchema = new Schema({
username: {type: String, required: true, index: {unique:true}},
password: {type: String, required: true, select: false}
})
userSchema.pre('save', function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
})
});
userSchema.methods.comparePassword = function(password){
var user = this;
bcrypt.compare(password, user.password, function(err, result){
if(err){
console.log(err);
}
else {
console.log("passwords match!");
return;
}
})
}
var userModel = mongoose.model('users', userSchema);
//Connecting to Mongo
mongoose.connect("mongodb://localhost/userstories", function(err){
if(err) {
console.log(err);
}
else {
console.log("Connected to database!");
}
});
//Creating Token
function createToken(user){
var token = webToken.sign({
_id: user.id,
username: user.username
}, secretKey,{
expiresIn: 30 * 60 * 1000
})
return token;
}
//Middlewares
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
//Api's
app.post('/signup', function(req, res){
var user = new userModel({
username: req.body.username,
password: req.body.password
})
user.save(function(err){
if(err){
console.log(err);
}
else{
res.json({message: "User created!"});
}
})
})
app.post('/login', function(req, res){
userModel.findOne({username: req.body.username}, function(err, user){
if(err) console.log(err);
if(!user){
res.send("User not found!");
}
else if(user){
var validPassword = user.comparePassword(req.body.password);
if(validPassword){
var tokens = createToken(user);
res.json({
success: true,
message: "Successfully logged In",
token: tokens
});
}
else {
res.send("Invalid password");
}
}
})
});
//Running the server
app.listen(3000, function(err){
if(err) console.log("port not working");
else{
console.log("Everything went just fine");
}
})
I've tried every approaches and saw all the answers here. But no one seem to come across this illegal argument error. Please figure this one out for me Im sure there is a bug I cant see
In your User Schema, you are setting select to false for the password field. This means that anytime you look for a user in the schema as you're trying to do in the login request, you won't get the value of the password field or any other field that has select false defined in the schema.
What you need to do is to specify you need the password when the user is found:
app.post('/login', function(req, res){
userModel.findOne({username: req.body.username}, 'password', function(err, user){
// continue
}
This will return only the _id and the password from the DB. If you want to return other fields, you'd have to add them in:
app.post('/login', function(req, res){
userModel.findOne({username: req.body.username}, 'password firstName lastName email', function(err, user){
// continue
}
I have tried the same code for authentication once and got the same error Error: Illegal arguments: string, function.
But I did not see any issue with the code. The thing is, I had registered two users with the same user name and a different password. Then, when I tried to log in with the user name and one password this error occurred and stopped the server.
So it seems that you are also facing the same problem. Make sure there are no errors with this stuff if you do not want to have a bug in your code.
Check the value of user.password before sending it to bcrypt.compare().
Chances are, you've fetched the user without including the password property, resulting in a value of undefined. This can happen in Sequelize if you set custom attributes or if you're using a scope that excludes props.
Your code is wrong in this place. You may see it.
var validPassword = user.comparePassword(req.body.password);
If you use bcryptjs thrid party plugins, like that
let validPassword = bcrypt.compare(req.body.password, user.password);
bcrypt.compare(password, hashedPassword);
In my particular case, I was dealing with this error, checking out all the code up and down unsuccessfully for almost two days.
Finally, realized that the column PASSWORD in MariaDB was in uppercase. Theoretically that shouldn't affect at all, but I decided to rename it to lowercase and bum! problem solved.
For those using async/await for database calls, make sure you don't forget the await keyword on the User.findOne() call.
In my case, I had forgotten the await keyword while fetching the user. This as a result, was giving me a Promise object instead of User object and hence the password property on it was undefined.
I also encountered the same error when I was using
bcrypt.compareSync("input to be compared with the hash", hash).
Later on I discovered that I was supposed to pass the actual value in the first input parameter i.e (The actual value from which the hash was generated) and the hash in the second input parameter, but I was passing hashed values in both the input parameters.
After correcting the same it was giving me the desired output as true or false.
You can also run and check your code here.
Do like this:
UserSchema.pre('save', async function (next) {
const hash = await bcrypt.hash(this.password, 10);
this.password = hash;
next()
})
You need to specify that you also want the password because you have set the select property to false on password.
So when you are fetching the user, just make sure to explicitly specify that you also want the password. Add .select('+password') on the user object when you are querying a user.
In my case it was a simple spelling mistake before sending to bcrypt.hash :
If you're testing this with Postman, I just found an issue where the default Content-Type header is set to text/plain. If you untick the default header (as it doesn't allow you to change it) and add another Content-Type header with a value of application/json, it works.
When i'm getting to my routes and requesting to getUSers from my mongoDB it says the User.find() is not defined. Sorry in advance if i use incorrect terminology i'm jumping in face first.
I'm assuming my routing is done incorrectly somewhere or i didn't include one file somewhere I'm hoping ya'll can help me determine if i'm either storing a file incorrectly in my structure, calling a file at the wrong time, or not initializing a variable correctly? Thanks for the help in advance.
Do i need an additional plugin to read and write to the database?
I keep getting the the following error it says usercontroller.js:20
Error: <!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>undefined is not a function</h1><h2></h2><pre>TypeError: undefined is not a function
at getUsers (c:\Users\Ravenous\kitchen\routes\user_api.js:5:10)
at c:\Users\Ravenous\kitchen\routes\user_api.js:26:3
file structure in case it helps
-bin
-node_modules-\
-user-app-\
-user.js //this is the model written with mongoose schema
-public-\
-html
-images
-javascripts-\
-userController
-userService //AngularJS factory
-stylesheets
-index.html
-routes-\
-user_api.js //with other useful routes inside.
-views //has some jade view engines that came with express-generator
-app.js
-package.JSON
I have this for the user model -- file: node_modules/user-app/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
user_name: String,
password: String,
email: String,
location: String,
date_created : {type: Date, default: Date.now}
});
var User = mongoose.model('User', UserSchema);
module.exports= {User:User};
I then import user.js file to the ./routes/user_api.js file which looks like this
user_api.js :
var User = require('./node_modules/user-app/user');
function getUsers(res){
User.find().populate('users').exec(function(err, users){
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err){
res.send(err)
}else{
console.log(users[0][0].name)
res.json(users); // return all users in JSON format
db.close();
}
})
};
module.exports = function(app) {
// api -----------------------------------------------------------
// get all users
app.get('/node_modules/user-app/user', function(req, res) {
// use mongoose to get all users in the database
getUsers(res);
});
// create user and send back all users after creation
app.post('/node_modules/user-app/user', function(req, res) {
// create a user, information comes from AJAX request from Angular
User.create({
user_name: User.user_name,
password: User.password,
email: User.email,
location: User.location,
done : false
}, function(err, todo) {
if (err){
res.send(err);
}else{
// get and return all the users after creating one
getUsers(res);
}
});
});
// delete a user
app.delete('/node_modules/user-app/user:user_id', function(req, res) {
User.remove({
_id : req.params.user_id
}, function(err, user) {
if (err)
res.send(err);
getUsers(res);
});
});
};
I'm adding this user_api route and get method to the app.js file like so
// loading some required modules above this
var app = express();
var user = require('./routes/user_api')(app);
to handle the Angular and Node connection and state sharing i'm using the following
userController.js:
(function(){
'use strict'
var userCtrl = angular.module("userController",[]);
console.log('userController init')
userCtrl.controller('UserController', ['$scope','$http','Users',function($scope,$http,Users){
$scope.users = {};
$scope.loading = true;
console.log ("user init");
Users.get()
.success(function(data){
$scope.users = data;
$scope.loading = false;
console.log(data)
})
.error(function(err){
console.log('Error: ' + err);
});
$scope.createUser = function(){
if($scope.users.user_name != false){
console.log($scope.users.user_name)
$scope.loading = true;
Users.create($scope.users)
.success(function(data){
$scope.loading=false;
$scope.users = data;
console.log(data);
})
.error(function(err){
console.log('Error: ' + err);
});
}
};
}]);
})();
Change the line where you require User to
var User = require('./node_modules/user-app/user').User;
This is because in your export statement when you define a user you have the line:
module.exports = {User:User};
So, you are exporting an object that has a User property on it.
Anyone got a migrate module that they use to migrate mongodb data with the mongoose plugin?
I am currently using the 'migrate' module and it works great except for the fact that I need to create/destroy my connection in each up/down.
I.E.
// Setup mongoose
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
exports.up = function(next) {
// get a brand new connection for this patch.
mongoose.connect('mongodb://localhost/sagedb');
var adminUser = {
username: 'admin',
password: 'admin'
};
User.createUser(adminUser, function(err, user) {
if (err) {
mongoose.disconnect(); // Make sure to close connection
return next(err);
}
mongoose.disconnect(next); // Make sure to close connection
});
};
exports.down = function(next) {
mongoose.connect('mongodb://localhost/sagedb'); // new connection for down
User.getUserByUsername('admin', function(err, user) {
if (err) {
mongoose.disconnect(function() { // make sure to close connection
return next(err);
});
}
if (!user) {
mongoose.disconnect(); // make sure to close connection
return next();
}
User.deleteUser(user, function(err, user) {
console.log('deleted user');
mongoose.disconnect(next); // make sure to close connection
});
});
};
Probably a much better way to do this. Wondering if the only option is to create my own module that starts the connection once and closes it when all patches are complete.
I have seen mongoose-migrate which tracks migration in database collection. Not really specific to mongoose IMHO, I would rather still use the .migrate file but only have to open the connection once.
The reason of the issue is that you have connection "connected" each time, on every ,migration
That is why you have to disconnect.
The same situation if you replace connect with mongoose.createConnection. you will need to close it.
How to solve?
move
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
into module like db
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
module.exports = mongoose
and just require it
var mongoose = require('./db')
So you will have:
Single connection
All models loaded in one place
Clean code in
migrations
You can also try my migrate-mongoose migration framework which provides the mongoose connection right out of the box.
in your up or down function you can just access your models like this
this('user').findOne({ name: 'Sergey' });
It also persists your migrations to the database instead of the file system.
You also have east migration framework that is very powerful and it also has mongoDB adaptors:
https://github.com/okv/east
Then you will crate migration with command:
east create my_migration_name
And then your migration scripts will look like this:
exports.migrate = function(client, done) {
var db = client.db;
db.........
done();
};
exports.rollback = function(client, done) {
var db = client.db;
db.........
done();
};