Database is not creating using express and node.js - node.js

I am working on simple registration page using express and mongodb this is my html
<body>
<form>
<div align="center" ng-controller="regiCtrl">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" ng-model="user.userName" />
</td></tr>
<tr>
<td>Password :</td>
<td><input type="password" ng-model="user.password" />
</td></tr>
<tr>
<tr><td>
<input type="button" value = "Submit" ng-click="regi()"></td>
<td>
</td></tr>
</table>
</div>
</form>
</body>
and this is my controller
lyfee.controller('regiCtrl',['$scope','$http', function($scope,$http) {
$scope.user = {};
$scope.regi = function () {
// var data = {User: $scope.user }
console.log($scope.user);
$http.post('/regi',$scope.user);
console.log("post request send");
}
}]);
have a look of my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
//Used for open index.html by default(open html page which one will be in public folder)
app.use(express.static(__dirname + "/public"));
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: 'anystringoftext',
saveUninitialized: true,
resave: true}));
app.use('/', function(req, res){
//res.send('Our First Express program!');
//res.redirect('index.html');
//console.log(req.cookies);
// console.log(req.session);
console.log("HELLO WE ARE IN SERVER");
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lyfee_module');
console.log("Connection created");
var Userschema = require('./models/dbSchema');
app.post('/regi',function(req,res){
console.log("post request get");
/*
var schema = new Userschema();
schema.Firstname = req.body.Firstname;
schema.Lastname = req.body.Lastname;
schema.City = req.body.city;
schema.Email = req.body.email;
schema.Userid = req.body.userid;
schema.Password = req.body.password;
console.log(schema.Firstname);
// console.log(schema.Lastname);
*/
console.log(req);
var schema = new Userschema({
userName : req.body.userName,
password : req.body.password,
});
console.log(req.body);
console.log(schema);
schema.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Record Inserted', userName: req.body.userName, password: req.body.password});
});
});
app.listen(port);
console.log('Server running on port: ' + port);
it's my config.js
module.export = {
'secret' : 'lyfee',
'database': 'mongodb://localhost/lyfee_module'
};
and finally is my db
var mongoose = require('mongoose');
var User = new mongoose.Schema({
userName: String,
password: String,
});
//console.log(User);
module.exports = mongoose.model('user', User);
my entries is not storing in database even database with lyfee_module is not creating please help me, how to i can solve this problem ?

i think every thing is looking fine just add running port of mongodb in config.js like
mongodb://localhost:27017/

Have you tried using a callback with mongoose.connect()? I would recommend trying the following and see if you get any errors:
mongoose.connect(mongoUrl, err => {
console.log(err || `MongoDB connected at ${mongoUrl}`);
})

Related

Why won't any of my http methods work from my new router folder? and how can I fix it?

This is my first web dev project. I am basically trying to make a simple website to sell light sabers. The goal is to be able to create an account, login, add, edit and delete light sabers. Be able to add them to cart and checkout. I am using node.js, express, and mongoDB in visual studio code. I am also learning github throughout the process. As of now I have the layout of the website mostly set up. Am able to create accounts and login. I am currently stuck on creating items(light sabers) and saving them in the mongoDB database. Specifically my http methods in the routes/items files are not working, they were working previously in the app.js file but I decided to move everything for organizational purposes. Again, this is my first time working with any of this tech and this project is a work in progress, any input is appreciated. Thanks.
Here is my code: There is a lot of code not being used and its kind of a mess. I know..
app.js file:
const express = require("express");
const session = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require('body-parser');
var localStrategy = require('passport-local');
var passportLocalMongoose = require("passport-local-mongoose");
var router = express.Router();
const app = express();
const indexRouter = require('./routes/index')
const itemsRouter = require('./routes/items')
//npm install ejs body-parser mongoose passport passport
var uri = "mongodb://username:password#cluster0-shard-00-00-
hnxfk.mongodb.net:27017,cluster0-shard-00-01-
hnxfk.mongodb.net:27017,cluster0-shard-00-02-
hnxfk.mongodb.net:27017/test?
ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority";
var localHost = "mongodb://localhost:27017/Project2SamJoshEricRoy"
mongoose.connect(uri,{useNewUrlParser: true, useUnifiedTopology:
true });
var User = require('./models/user');
var Item = require('./models/item');
// var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(require('express-session')({
secret: "application secret shhhh",
resave: false,
saveUninitialized: false
}));
passport.use(new localStrategy(User.authenticate()))
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter)
app.use('/items', itemsRouter)
//create account
app.get("/createAccount",(req,res)=> {
res.render("createAccount");
});
app.get('/createAccount', function(req,res) {
res.render('createAccount');
});
app.post("/createAccount",(req,res)=> {
req.body.username;
req.body.password;
User.register(new
User({username:req.body.username}),req.body.password,
(err,user) =>{
if(err) {
console.log(err);
return res.render("createAccount");
}
passport.authenticate("local")(req,res,() => {
res.redirect('/login');
console.log(req.body.username
+ " " + req.body.password);
console.log(user);
});
});
});
//login
app.get("/login",(req,res) => {
res.render("login")
User.find(function(err,users) {
if(err) {
console.log(err);
}
// console.log(users);
})
});
app.post('/login',passport.authenticate("local",{
successRedirect: "/lightsabers",
failureRedirect: "/login"
}),(req,res)=> {
});
function isLoggedIn(req,res,next) {
console.log("CALL")
if(req.isAuthenticated()) {
console.log("logged in ");
return next();
}
res.redirect("/login");
console.log("error logging in");
}
//logout
app.get("/logout",(req,res)=> {
req.logout();
res.redirect('/');
});
//lightsabers
//app.get("/lightsabers",isLoggedIn,(req,res)=> {
//res.render("lightsabers",{user: req.user});
//console.log(req.user);
//});
//shopping cart
app.get("/cart",(req,res)=> {
res.render("cart");
});
app.get('/createLightsaber',(req,res)=> {
res.render("newItem",{user:req.User});
console.log("user is with us");
console.log(req.user)
});
app.get('/updateItem',(req,res)=> {
res.render("updateLightsaber");
});
app.get('/deleteLightsaber',(req,res)=> {
res.render("updateLightsaber");
});
/routes/index.js file:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('index')
})
module.exports = router
routes/items.js
const express = require('express')
const router = express.Router()
const Item = require('../models/item')
//display page
router.get("/",(req,res)=> {
res.render("newItem");
});
// all items route
router.get('/', async (req, res) =>{
try{
const items = await Item.find({})
res.render('items/newItem', {item: new Item() })
} catch {
res.redirect('/')
}
})
//new item route (display form)
router.get('/newItem', (req, res) => {
res.render('items/newItem', {item: new Item() })
})
// create new item route (actual creation)
router.post('/newItem', async (req,res) => {
const item = new Item({
color:req.body.color,
price:req.body.price,
link:req.body.link
})
try{
const newItem = await item.save()
res.redirect('lightsabers')
} catch {
res.render('items/newItem', {
item: item,
errorMessage:'Error creating item'
})
}
})
/update item
app.get("/updateItem",(req,res)=> {
res.render("updateItem");
});
module.exports = router
newItem.ejs
<!DOCTYPE html>
<html>
<head>
<title> </title>
<link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h1> Adding New Item </h1>
<form action="/items" method="POST">
<h2>
Color: <input type="text" name="color"><br>
Price: <input type="text" name="price"><br>
Image Link:<input type="text" name="link"><br>
<br><br>
<button id="addItem">Add Item</button>
<%= typeof(message) != "undefined"?message:"" %>
</h2>
</form>
<form action="/lightsabers">
<h2><button> Back </button></h2>
</form>
<script type="text/javascript" src="../public/app.js">
</script>
</body>
</html>
If you wish to see any other parts of the code let me know. I may be forgetting something important.

passport-local-mongoose: No response

When authenticating with the server, the server does not respond to the POST request. The server recieves the requesst and parses the JSON correctly, but it never sends the response. I have followed many guides and updated Node to no avail.
The code is fairly straightforward, the relevant parts are:
app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoose = require('mongoose');
var connectMongo = require('connect-mongo');
var debug = require('debug')('sess:app');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var index = require('./routes/index');
var home = require('./routes/home');
var about = require('./routes/about');
var catalog = require('./routes/catalog');
var branches = require('./routes/branches');
var users = require('./routes/users');
var dbconnect = require('./dbconnect');
var app = express();
var MongoStore = connectMongo(session);
var sessionConnect = dbconnect.Session;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(cookieParser());
app.use(session({
name: '...',
secret: '...',
resave: false,
saveUninitialized: false,
rolling: true,
store: new MongoStore({ mongooseConnection: sessionConnect }),
cookie: { maxAge: 900000, httpOnly: true, sameSite: true }
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// passport setup
var User = require('./models/user')(dbconnect.Models);
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Create user for testing
User.create({username:'admin',password:'12345',deleted:false,kind:'manager'});
// login
// This was attempted with additional redirection options as well
app.post('/login', passport.authenticate('local'), function(req, res) {
// This message never appears in the log
console.log('auth');
res.status(200).end();
});
// logout
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
dbconnect.js:
var mongo = require("mongoose");
mongo.Promise = global.Promise;
var debug = require('debug')('sess:app');
function dbconnect(path){
var userConnStr = 'mongodb://localhost:27017/ise_' + path + '_v6';
var db = mongo.createConnection()
db.on('connecting', function() { debug('Connecting to MongoDB: '); });
db.on('connected', function() { debug('Connected to MongoDB: '); });
db.on('disconnecting', function() { debug('Disconnecting to MongoDB: '); });
db.on('disconnected', function() { debug('Disconnected to MongoDB: '); });
db.on('reconnected', function() { debug('Reconnected to MongoDB: '); });
db.on('error', function(err) { debug('Error to MongoDB: ' + err); });
db.on('open', function() { debug('MongoDB open : '); });
db.on('close', function() { debug('MongoDB close: '); });
process.on('SIGINT', function() { db.close(function () { process.exit(0); });});
db.openUri(userConnStr);
console.log('Pending DB connection');
return db;
};
module.exports = {Session: dbconnect('session'), Models: dbconnect('models'), Custom: dbconnect};
models/user.js:
var mongo = require("mongoose");
var Schema = mongo.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var userSchema = new Schema({ // create a schema
name: { first: String, last: String }, // field-object (with sub-fields)
kind: { type: String, required: true, enum: ["manager", "employee", "customer", "supplier"] },
email: String,
branch: Number,
created_at: Date,
updated_at: Date,
deleted: { type: Boolean, required: true }
});
userSchema.plugin(passportLocalMongoose);
userSchema.methods.remove = function() {
deleted = true;
save();
};
// on every save, add the date
userSchema.pre('save', function(next) { //callback
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
module.exports = function(db){
return db.model('User', userSchema);
};
The client code uses AngularJS v1:
Controller function:
$scope.signin = function(){
$http.post("login", {'username': $scope.username, 'password': $scope.password}).then(function(data){
// ......
}, function(data){
alert("Wrong username or password");
});
};
HTML Bootstrap modal:
<div id="signInModal" class="modal fade" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign in</h4>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<input ng-model="username" type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input ng-model="password" type="password" placeholder="Password" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" ng-click="signin()">Sign in</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>

SMS reminder app, Node/Twilio/Cron/Mongo: TypeError: Cannot read property 'utc' of undefined

I'm working off of some code in a Twilio tutorial, and everything seems to be working fine, except I'm not receiving any notifications. I get this error back after the Notifications Worker runs:
[grunt-develop] > (node:58755) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'utc' of undefined
Here is the appointment.js file that appears to be causing the error under AppointmentSchema.methods:
var mongoose = require('mongoose');
var moment = require('moment');
var twilio = require('twilio');
var AppointmentSchema = new mongoose.Schema({
phoneNumber: String,
notification : String,
timeZone: String,
time : {type : Date, index : true}
});
AppointmentSchema.methods.requiresNotification = function (date) {
return Math.round(moment.duration(moment(this.time).tz(this.timeZone).utc()
.diff(moment(date).utc())
).asMinutes()) === this.notification;
};
AppointmentSchema.statics.sendNotifications = function(callback) {
// now
var searchDate = new Date();
Appointment
.find()
.then(function (appointments) {
appointments = appointments.filter(function(appointment) {
return appointment.requiresNotification(searchDate);
});
if (appointments.length > 0) {
sendNotifications(appointments);
}
});
// Send messages to all appoinment owners via Twilio
function sendNotifications(docs) {
var client = new twilio.RestClient(ACCOUNTSID, AUTHTOKEN);
docs.forEach(function(appointment) {
// Create options to send the message
var options = {
to: "+1" + appointment.phoneNumber,
from: '+17755834363',
body: "Just a reminder that you have an appointment coming up " + moment(appointment.time).calendar() +"."
};
// Send the message!
client.sendMessage(options, function(err, response) {
if (err) {
// Just log it for now
console.error(err);
} else {
// Log the last few digits of a phone number
var masked = appointment.phoneNumber.substr(0,
appointment.phoneNumber.length - 5);
masked += '*****';
console.log('Message sent to ' + masked);
}
});
});
// Don't wait on success/failure, just indicate all messages have been
// queued for delivery
if (callback) {
callback.call(this);
}
}
};
var Appointment = mongoose.model('appointment', AppointmentSchema);
module.exports = Appointment;
I have no idea why it's undefined, everything appears to be showing up fine in the db. And I don't know if this is what is causing the notifications to not actually be sent. I've been laboring over this for some time, if anyone has any insight that would be great.
File structure:
root
├ config
| ├ auth.js
| ├ database.js
| ├ passport.js
├ controllers
| ├appointments.js
| ├routes.js
├ models
├appointment.js
├users.js
├ public
├ workers
├notificationsWorker
├ app.js
├ scheduler.js
Other relevant files to notifications:
appointments.js
var momentTimeZone = require('moment-timezone');
var Appointment = require('../models/appointment');
var moment = require('moment');
module.exports = function(app, client) {
app.post('/user', function(req, res, next) {
var phoneNumber = req.body.phoneNumber;
var notification = req.body.notification;
var timeZone = req.body.timeZone;
var time = moment(req.body.time, "MM-DD-YYYY hh:mma");
var appointment = new Appointment({
phoneNumber: phoneNumber,
notification: notification,
timeZone: timeZone,
time: time
});
appointment.save()
.then(function () {
res.redirect('/user');
});
});
notificationsWorker.js
var Appointment = require('../models/appointment')
var notificationWorkerFactory = function(){
return {
run: function(){
Appointment.sendNotifications();
}
};
};
module.exports = notificationWorkerFactory();
scheduler.js
var CronJob = require('cron').CronJob;
var notificationsWorker = require('./workers/notificationsWorker');
var moment = require('moment');
var schedulerFactory = function(){
return {
start: function(){
new CronJob('00 * * * * *', function() {
console.log('Running Send Notifications Worker for ' + moment().format());
notificationsWorker.run();
}, null, true, '');
}
};
};
module.exports = schedulerFactory();
And finally the app.js file:
const dotenv = require('dotenv').config({path: '.env'});
const exp = require('express');
const bodyParser = require('body-parser'); //body parser
const methodOverride = require('method-override'); //method override
const app = exp();
const session = require('express-session');
const PORT = process.env.PORT || 3000;
const fetchUrl = require('fetch').fetchUrl;
const request = require('request');
const sass = require('node-sass');
const exphbs = require('express-handlebars');
const favicon = require('serve-favicon');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
var appointments = require('./controllers/appointments');
var scheduler = require('./scheduler');
var ACCOUNTSID = process.env.TWILIO_ACCOUNT_ID;
var AUTHTOKEN = process.env.TWILIO_AUTH_TOKEN;
var twilio = require('twilio');
var client = new twilio.RestClient(ACCOUNTSID, AUTHTOKEN);
//databse stuff
const db = require('./config/database.js');
// mongoose.connect(db.url); // connect to our database
//passport
const passport = require('passport');
const flash = require('connect-flash');
app.use(session({ secret: 'blahblahblahbleck' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
//views/middleware configs
app.engine('handlebars', exphbs({
layoutsDir: __dirname + '/views/layouts/',
defaultLayout: 'main',
partialsDir: [__dirname + '/views/partials/']
}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.locals.pretty = true
app.use('/', exp.static(__dirname + '/public'));
app.use('/bower_components', exp.static(__dirname + '/bower_components'));
app.use(methodOverride('_method')) //method override
app.use(bodyParser.urlencoded({
extended: false
// app.use(favicon(__dirname + '/public/imgages/favicon.ico'));
})); //body parser
app.use(bodyParser.json()); //body parser
app.use(cookieParser());
app.use(morgan('dev'));
app.locals.moment = require('moment');
require('./config/passport')(passport);
require('./controllers/routes')(app, passport);
require('./controllers/appointments')(app, client, db);
app.use('./controllers/appointments', appointments);
app.use('/', appointments);
// dynamically set controllers(routes)
fs.readdirSync('./controllers').forEach(function(file) {
routes = require('./controllers/' + file);
});
//start the server
app.listen(PORT, function() {
console.log('things that make you go hmmm on port ' + PORT);
});
scheduler.start();
module.exports = app;
==================UPDATED=================
My form input view:
<form class="omb_loginForm" action="/" autocomplete="off" method="POST">
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<input type="text" class="form-control" name="phoneNumber" placeholder="phone number">
</div>
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<input type="text" class="form-control" name="notification" placeholder="notification">
</div>
<span class="help-block"></span>
<div class="input-group">
<span class="input-group-addon"></span>
<select class="form-control" name="timeZone">
{{#each timeZone}}
<option>{{this}}</option>
{{/each}}
</select>
</div>
<span class="help-block"></span>
<div class="input-group date" id="datetimepicker1">
<input class="form-control" name="time">
<span class="input-group-addon glyphicon-calendar glyphicon">
</span>
</div>
<span class="help-block"></span>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
Original form view:
.form-group
label.col-sm-4.control-label(for='inputName') Name *
.col-sm-8
input#inputName.form-control(type='text', name='name', placeholder='Name', required='', data-parsley-maxlength='20', data-parsley-maxlength-message="This field can't have more than 20 characters", value="#{appointment.name}")
.form-group
label.col-sm-4.control-label(for='inputPhoneNumber') Phone Number
.col-sm-8
input#inputPhoneNumber.form-control(type='number', name='phoneNumber', placeholder='Phone Number', required='', value="#{appointment.phoneNumber}")
.form-group
label.col-sm-4.control-label(for='time') Appointment Date
.col-sm-8
input#inputDate.form-control(type='text', name='time', placeholder='Pick a Date', required='', value="#{moment(appointment.time).format('MM-DD-YYYY hh:mma')}")
.form-group
label.col-sm-4.control-label(for='selectNotification') Notification Time
.col-sm-8
select#selectDelta.form-control(name='notification', required='', value="#{appointment.notification}")
option(selected=appointment.notification == '', value='') Select a time
option(selected=appointment.notification == '15', value='15') 15 Minutes
option(selected=appointment.notification == '30', value='30') 30 Minutes
option(selected=appointment.notification == '45', value='45') 45 Minutes
option(selected=appointment.notification == '60', value='60') 60 Minutes
.form-group
label.col-sm-4.control-label(for='selectTimeZone') Time Zone
.col-sm-8
select#selectTimeZone.form-control(name='timeZone', required='', value="#{appointment.timeZone}")
each zone in timeZones
option()
option(selected=zone == appointment.timeZone, value="#{zone}") !{zone}
routes.js
app.get('/user', isLoggedIn, function(req, res) {
res.render('user', {
user : req.user,
timeZone: timeZones(),
appointment : new Appointment({
phoneNumber: "",
notification: '',
timeZone: "",
time:''}),
loggedIn: true, // get the user out of session and pass to template
layout: 'home'
});
});
I was able to finally get it working by changing the logic around in requiresNotification. Here's the updated code:
AppointmentSchema.methods.requiresNotification = function (date) {
var apptDate = moment.utc(this.time);
var current = moment.utc(date);
return Math.round(moment.duration(current.diff(apptDate))
.asMinutes()) === 0;
};
I'm finding the duration of the difference between the appointment time and current time. So now when the difference in minutes of the appointment date/time and the current date/time is 0, the notification is sent.

Saving data to mongodb database issues using nodejs and express

I am having an issue with trying to save data parsed from the browser to my mongodb database it would be great if someone could explain to me why I am getting the error I am and how to fix it, thanks.
App.js:
var print = require('./print');
var port = 1338;
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:1337/testdb';
MongoClient.connect(url, function(err, db) {
var collection = db.collection('users');
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
}
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
var collection = db.collection('users');
var name = app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
var name = req.body.name
var user1 = { "username": name };
collection.insert(user1, 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);
}
})
});
app.listen(port, function() {
print(`listening on ${port}`);
})
db.close();
})
Post.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="http://127.0.0.1:1338/post" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
Error:
{ MongoError: server instance pool was destroyed
at Function.MongoError.create (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\error.js:29:11)
at basicWriteValidations (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:446:51)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:532:16)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\\node_modules\mongodb\lib\server.js:383:17)
at executeCommands (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:455:23)
at OrderedBulkOperation.execute (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:508:10)
at bulkWrite (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:652:8)
at Collection.insertMany (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:522:44)
at Collection.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:824:15)
at C:\Users\Programming\Documents\Web_Repo\app.js:36:18
name: 'MongoError',
message: 'server instance pool was destroyed' }
Looks like Mukesh already told you the solution but like he mentioned your code structure can be improved.
So here's how I would do it,
Config file ~config.js
module.exports = {
localUrl: 'mongodb://localhost/testDb',
port: 1338
};
main file
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
collection.insert({
username : req.body.name
}, function(err, result) {
if (err) {
console.log(err);
db.close();
return;
}
db.close();
})
});
})

how to connect html page with nodejs

Iam not able to get the html page.My nodejs is connecting with mongodb but when iam getting values from html page the values are not storing in db.Iam not able establish the connection from frontend to db at a time.help me out
this is my login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="/" method="POST">
<center>
User Name: <input type="text" name="username"> <br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and this is my login.js code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/logindb';
var loginSchema = mongoose.Schema({
username: String,
password: String
});
mongoose.connect(url);
app.get('/login.html', function(req, res) {
res.sendFile(__dirname + "/" + "login.html");
})
app.post('/', function(req, res) {
var Book = mongoose.model('book', loginSchema);
var book1 = new Book({
username: req.body.username,
password: req.body.password
});
book1.save(function(err) {
if (err) throw err;
console.log("Login saved succesfully");
res.end('success');
}
);
});
app.listen(8000, function() {
console.log("Server is running!");
});
For using req.body.username you need to use body-parser module,
install: npm install body-parser -S
Code:
var express = require('express'),
app = express(),
bodyparser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Resources