I just tried to create simple login and registration form with mongodb version 3.2.21 because I've got Windows 7 with 32bit CPU so here is the code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var consolidate = require('consolidate');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer')
var upp = multer()
var bodyParser = require('body-parser')
var router = express.Router()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(upp.array());
app.use(express.static('public'));
app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoDB = 'mongodb://localhost/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true});
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
if(db){
console.log('connection')
}
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
username: String,
password: String
});
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
var newuser = new SomeModel();
app.get('/', function(req, res){
res.render('mainpage')
})
app.get('/reg', function(req, res){
res.render('reg')
})
app.post('/reeg', function(req,res){
newuser.username = req.body.username;
newuser.password = req.body.password;
newuser.save(function (err, savedObject){
if (err){
console.log(err)
}else{
console.log(savedObject);
res.sendFile(__dirname + '\\views\\mainpage.html')
}})
});
app.post('/login', function(req,res){
var userr = req.body.usernamee
var pass = req.body.passwordd
newuser.findOne({username: userr, password: pass}).exec(),
function(err,obj){
if(err) {return res.status(404)
}else if(!obj){
res.send('notregistered')
}if(obj){
res.send('hey' + userr)
}
}})
http.listen('8080')
and this is giving me this error
So what is problem here? I am not using express router yet and this code is in one file
newuser is not a model, it's an instance of SomeModel - list of methods here
findOne is method of model - SomeModel list of methods here
so replace: newuser.findOne to SomeModel.findOne
I've rewritten overall code for better readability, async/await features, with object destructuring examples and etc best practices:
'use strict';
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const bodyParser = require('body-parser');
const consolidate = require('consolidate');
// DB connection
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost/my_database';
mongoose.Promise = global.Promise;
mongoose
.connect(connectionString, {useNewUrlParser: true})
.then(() => {
console.log('Connection to database established');
})
.catch(error => {
console.error('MongoDB connection error:', error.message);
process.exit(-1);
});
// End of: DB connection
// Defining DB schemas and models
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
password: String
});
const User = mongoose.model('User', UserSchema);
// End of: Defining DB schemas and models
// Initial app configuration
const app = express();
const server = http.Server(app);
const io = socketIO(server);
app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// End of: Initial app configuration
// App route handlers
app.get(
'/',
(req, res) => {
res.render('mainpage');
});
app.get(
'/reg',
(req, res) => {
res.render('reg');
});
app.post(
'/reg',
async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.create({username, password});
console.log('Created user:', user);
res.sendFile(path.join(__dirname, 'views', 'mainpage.html'));
}
catch (error) {
res.status(500).send(error.message);
}
});
app.post(
'/login',
async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.findOne({username, password}).select('-password').lean();
if(!user) {
res.send('User: ' + username +' not registered');
return;
}
res.send('hey ' + username);
}
catch (error) {
res.status(500).send(error.message);
}
});
// End of: App route handlers
// Binding http listener to port
server.listen('8080');
Notice: lean is method of query manual here
Fix Your login form:
<form action="/login" method="POST">
<input type="text" placeholder="username" name="username">
<input type="password" placeholder="pass" name="password">
<button type="submit">Login</button> <br/>
or <strong>Sign Up</strong>
</form>
P.S. Write in comments if something will go wrong.
Related
Not sure why this is happenening, tried removing all instances of new, switching to let from const ect. Can run site however when I run a post request via a html form, get an error on the line "const user = new UserSchema" ect. of TypeError: UserSchema is not a constructor.
const express = require('express');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bodyParser = require('body-parser');
let app = express();
let mongoDB = //hiding url for obvious reasons
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
const UserSchema = new Schema({
name: String,
email: String
});
app.set('view engine', 'ejs');
app.use('/assets', express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req,res){
res.render('landingPage');
});
app.post('/', function (req, res) {
const user = new UserSchema(req.body.name, req.body.email);
user.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(3000);
You have to assign the schema as a mongoose model.
var User= mongoose.model('user', UserSchema);
I am trying to run my webapp using mongodb but I am constantly getting error of app crashed. I have rechecked everything but it is still causing error. Can anyone help me with it?
server.js:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
const express = require('express')
const app = express()
const expressLayouts = require('express-ejs-layouts')
const indexRouter = require('./routes/index')
const authorRouter = require('./routes/authors')
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.set('layout', 'layouts/layout')
app.use(expressLayouts)
app.use(express.static('public'))
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose'))
app.use('/', indexRouter)
app.use('/authors', authorRouter)
app.listen(process.env.PORT || 3000)
author.js
const mongoose = require('mongoose')
const authorSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
})
module.exports = mongoose.model('Author', authorSchema)
I have separate folder for routes for authors. The above author is author model and this one file is for /authors route.
authors.js:
const express = require('express')
const router = express.Router()
const Author = require('../models/author')
// All Authors Route
router.get('/', (req, res) => {
res.render('authors/index')
})
// New Author Route
router.get('/new', (req, res) => {
res.render('authors/new', { author: new Author() })
})
// Create Author Route
router.post('/', (req, res) => {
res.send('Create')
})
module.exports = router
I get this error
[nodemon] app crashed - waiting for file changes before starting...
So I am trying to build an authentication system using passport in MERN(MongoDB, Express, React, NodeJS).
I set up everything, I connected react with NodeJS,
The problem is when I am trying to log in or register it shows me,
this error "User.findOne is not a function" in the console and I tried to fix it by looking for any
type mistakes or google it but I didn't find anything online.
Did anyone have a similar mistake and fix it or does anyone know how?
Model Code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const UserSchema = new Schema ({
password: String,
email: String,
}, {
collection: 'information'
})
const User = mongoose.model('information', UserSchema);
module.exports - User;
Passport Code:
const Strategy = require('passport-local').Strategy
const mongoose = require('mongoose')
const User = require('../models/user');
const bcrypt = require('bcryptjs')
const salt = bcrypt.genSaltSync(10);
const SignupStrategy = new Strategy ({ passReqToCallback:true, usernameField: 'email' }, function(req, email, password, done){
User.findOne({email: req.body.email}).lean().exec((err, user) => {
if (err) {
return done(err, null);
}
if (user) {
return done("User already exist", null);
}
const encryptedPassword = bcrypt.hashSync(password, salt);
let newUser = new User({
email,
password: encryptedPassword
})
newUser.save((error, inserted) => {
if (error) {
return done(error, null);
}
delete inserted.password;
return done(null, inserted);
})
})
});
module.exports = SignupStrategy;
Node server:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const passport = require('./passport/');
const PORT = process.env.PORT || 8080;
const mongoose = require('mongoose');
//I have used password in mongo I just did <password> for security reasons.
const mongoString = mongoose.connect('mongodb+srv://herpryth:<password>#nowyourguest-ga5vy.gcp.mongodb.net/users?retryWrites=true&w=majority', {useNewUrlParser: true})
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
app.use('/authentication', usersRouter);
app.use(passport.initialize());
app.use(passport.session());
app.listen(process.env.PORT || 8080, process.env.IP || '0.0.0.0');
module.exports = app
Route:
const express = require('express');
const app = express.Router();
const passport = require('../passport')
app.post('/signup', (req, res, next) =>{
passport.authenticate('local-signup', function(error, user, info){
if (error) {
return res.status(500).json({
message: error || 'Something happend',
error : error.message || "Server error"
});
}
return res.json(user);
})(req, res, next);
})
app.post('/signin', function(req, res, next){
passport.authenticate('local-signin', function(error, user, info){
if (error) {
return res.status(500).json({
message: error || 'Something happend',
error : error.message || "Server error"
});
}
return res.json(user);
})(req, res, next);
})
module.exports = app;
React server:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const passport = require('./passport/');
const PORT = process.env.PORT || 8080;
const mongoose = require('mongoose');
const mongoString = mongoose.connect('mongodb+srv://herpryth:XFXGJakc18wBJLIk#nowyourguest-ga5vy.gcp.mongodb.net/users?retryWrites=true&w=majority', {useNewUrlParser: true})
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
app.use('/authentication', usersRouter);
app.use(passport.initialize());
app.use(passport.session());
app.listen(process.env.PORT || 8080, process.env.IP || '0.0.0.0');
module.exports = app
Does anyone know how to fix this problem?
There is just a simple mistake in your code
replace with
module.exports = User
to
module.exports - User
When I did res.json (newschema) on post action, the properties are not displayed any more on Postman and also in Mongodb.
This is formations.routes
const express = require('express');
const router = express.Router();
const Formation = require('../models/formations');
const mongoose = require('mongoose');
const config = require('../config/database');
router.get('/', function(req, res){
//Formation.getFormations(function(err, formations){
// if(err)throw err;
// res.json(formations);
//});
Formation.find({})
.exec(function(err, Formations){
if(err){
console.log('error');
}else{
res.json(Formations);
}
})
});
router.post('/', function(req, res){
console.log('post a formations');
var newFormation = new Formation();
newFormation.title = req.body.title;
newFormation.url = req.body.url;
newFormation.description = req.body.description;
newFormation.save(function(err, newFormation){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
});
This is formation.models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const config = require('../config/database');
const FormationSchema = mongoose.Schema ({
title: String,
url: String,
description: String
});
module.exports = mongoose.model('Formation', FormationSchema, 'Formations');
This is my app.js ( endpoint)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const User = require('./models/user');
const Formation = require('./models/formations');
mongoose.connect(config.database , { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('connected to database... ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('database error'+err);
});
/*mongoose.connect('mongodb://localhost:27017/hello', { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected!');
});*/
const app = express();
const users = require('./routes/users');
const formations = require('./routes/formations');
//port number
const port = 3001;
//cors middleware
app.use(cors({
origin: 'http://localhost:4200'
}));
//passwport middelware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport); //pour implémenter fichier passport.js
//set static folder
app.use(express.static(path.join(__dirname + '/public')));
//BodyParser middleware
app.use(express.json());
app.use(bodyParser.json());
app.use('/users', users);//hedhiya ki nekteb /users barka f url yemchili direct lel const users = require('./routes/users'); fichier hedhka
app.use('/formations', formations);
//c un route
//just meloul 7atineha bch ntastiw beha
//index route
app.get('/', function(req, res){
res.send('invalid endpoint');
});
//start Server
app.use(bodyParser.urlencoded({extended:true}));
app.listen(port, () => {
console.log('Server started on port' +port);
});
And this is how I make a post action in Postman
The save method only has an error parameter in the callback. You are adding a newFormations parameter which will always be undefined and in the scope of the method you are returning undefined in the res.json call. To fix it remove the newFormation parameter as below:
newFormation.save(function(err){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
I'm trying to write an API using mongoose and mongolab.
Here is my code :
./index.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:pass#****.mlab.com:*****/****');
var Bear = require('./app/models/bear');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function(req, res, next){
console.log('request called');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'in /' });
});
router.route('/bears')
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function(err) {
console.log('in save')
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);
and
./app/models/bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
My problem is, when I try the following request :
It doesn't return anything. I tried to console.log something in bear.save but in never goes in.
I don't get what I am doing wrong. Also when I try to connect to my mongolab db from my terminal it works perfectly well.
There's a problem with your index.js. Here, use this code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Bear = require('./bear');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function (req, res, next) {
console.log('request called');
next();
});
router.get('/', function (req, res) {
res.json({
message: 'in /'
});
});
/*router.route('/bears')*/
router.post('/bears', function (req, res) {
console.log("request: " + JSON.stringify(req.body));
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function (err) {
console.log('in save')
if (err)
res.send(err);
res.json({
message: 'Bear created!'
});
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);