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();
})
});
})
Related
i tried to emplement socket.io but it does not show the way that it should be. Can anyone know where the problem. i tried to solve this around 2 weeks. Its headache to me. I tried many time already which is used emit,write, all of it. this is my code
HTML
<section class="msger" style="margin: auto;">
<header class="msger-header">
<div class="msger-header-title">
<i class="fas fa-comment-alt"></i> Chat
</div>
<div class="msger-header-options">
<span><i class="fas fa-cog"></i></span>
</div>
</header>
<main class="msger-chat" id="msger-chat">
</main>
<form class="msger-inputarea" >
<input type="hidden" name="booking" value="<%= booking %>">
<input type="hidden" id="name" class="form-control" readonly placeholder="Name"
value="<%= user.username %>">
<input type="text" name="user" value="<%= user._id %>">
<input id="message" type="text" class="msger-input" placeholder="Enter your message...">
<button id="send" type="submit" class="msger-send-btn">Send</button>
</form>
</section>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
</div>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<script type="text/javascript" src="/js/mdb.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<!-- Custom scripts -->
<script>
var socket = io();
$(() => {
$("#send").click(() => {
sendMessage({
booking: $("input[name=booking]").val(),
user: $("input[name=user]").val(),
message: $("#message").val()
});
})
getMessages()
})
socket.on('message', addMessages)
function addMessages(message) {
if (message.user && message.user != '') {
if ($("input[name=user]").val() == message.user._id) {
html = '<div class="msg right-msg"><div class="msg-img" style="background-image: url(' + message.user.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.user.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
} else {
html = '<div class="msg left-msg"><div class="msg-img" style="background-image: url(' + message.pro.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.pro.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
html += '<div class="msg-text">' + message.message + '</div></div></div>'
window.scrollTo(0, document.body.scrollHeight);
$("#msger-chat")+$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://127.0.0.1:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://127.0.0.1:3000/messages', message)
}
</script>
this is my routes
Route
var http = require('http').Server(router);
var io = require('socket.io')(http);
// Render Message
router.get('/messages/:id', async function (req, res, next) {
user = await User.findOne({_id: req.session.userId}, {username: 1})
return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});
// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
Message.find({booking: req.params.booking})
.populate({
path: "pro",
model: Pro,
}).populate({
path: "user",
model: User,
}).exec().then((data) => {
res.json(data)
})
})
router.post('/messages', async (req, res) => {
const {booking, user, message} = req.body
try {
var msg = new Message({
booking: booking,
message: message,
user: user
});
var savedMessage = await msg.save()
console.log('saved');
var censored = await Message.findOne({
message: 'badword'
});
if (censored)
await Message.remove({
_id: censored.id
})
else
io.emit('message', req.body);
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log('error', error);
} finally {
console.log('Message Posted')
}
})
Server
var express = require('express');
var env = require('dotenv').config()
var ejs = require('ejs');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session)
const cookieParser = require('cookie-parser')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
app.use(cors())
app.use(cookieParser());
// mongodb://localhost:27017 127.0.0.1:27017
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/findaprofessional', {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if (!err) {
console.log('MongoDB Connection Succeeded.');
} else {
console.log('Error in DB connection : ' + err);
}
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});
const oneDay = 1000 * 60 * 60 * 24;
app.use(session({
secret: 'work hard',
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: true
}));
// ni lain
app.set("view engine", "ejs")
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/css', express.static(path.resolve(__dirname, "asset/css")))
app.use('/img', express.static(path.resolve(__dirname, "asset/img")))
app.use('/js', express.static(path.resolve(__dirname, "asset/js")))
app.use('/vendor', express.static(path.resolve(__dirname, "asset/vendor")))
app.use('/lib', express.static(path.resolve(__dirname, "asset/lib")))
app.use('/scss', express.static(path.resolve(__dirname, "asset/scss")))
app.use('/pic', express.static(path.resolve(__dirname, "asset/img/pic")))
var index = require('./routes/index');
const { Socket } = require('socket.io');
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
io.on('connection', () =>{
console.log('a user is connected')
})
var server = http.listen(3000, () => {
console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});
Im expecting someone can go thru my codes and solve the problem. i thinks my problem at html socken.on. but im not sure enough.
When I try to add a post to the database the JSON Body is perfectly fine, but when I retrieve these it only shows id and __v (versionKey)
I've tried using body-parser in different ways, such as...
app.use('bodyParser.json()')
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var jsonParser = bodyParser.json();
The last two included in the app.post method.
This is my index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const port = 4000;
const postRoutes = express.Router();
let Post = require('./post.model');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var jsonParser = bodyParser.json();
app.use(cors());
app.use('/', express.static('public'));
app.use(bodyParser.json());
app.use('/posts', postRoutes);
mongoose.connect("mongodb://127.0.0.1:27017/mern-blog-test", { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Succesfully established connection to MongoDB Database');
})
postRoutes.route('/').get(function (req, res) {
Post.find(function (err, posts) {
if (err) {
console.log(err);
} else {
res.json(posts);
}
});
});
postRoutes.route(':id').get(function(req,res) {
let id = req.params.id;
Post.findById(id, function(err, post) {
res.json(post);
});
});
// todoRoutes.route('/add').post(function (req, res) {
// let todo = new Todo(req.body);
// todo.save()
// .then(todo => {
// res.status(200).json({ 'todo': 'todo added successfully' });
// })
// .catch(err => {
// res.status(400).send('adding new todo failed');
// });
// });
app.get('/create', function(req,res){
res.sendFile(__dirname + '/public/add.html');
})
app.post('/makepost', urlencodedParser, function(req,res) {
console.log(req.body);
let post = new Post(req.body);
post.save()
.then(todo => {
res.sendFile(__dirname + '/public/add.html')
})
.catch(err => {
res.status(400).send('adding new post failed!');
});
});
This is my form
<label for="title">Title</label>
<input type="text" name="title">
<label for="category">Category</label>
<select name="category">
<option>Coding</option>
<option>Music</option>
<option>Books</option>
<option>Other Stuff</option>
</select>
<label for="content">Content</label>
<input type="text" name="content">
<input type="submit">
</form>
And my post.model.js
const Schema = mongoose.Schema;
let Post = new Schema({
post_title: {
type: String
},
post_date: {
type: Date
},
post_shortdesc: {
type: String
},
post_content: {
type: String
}
});
module.exports = mongoose.model('Post', Post);
I expect the output to be...
[{"_id":"5d76a7e78b55cd3309b91ecf", "title": "blah", category: "blah", "content": "blah", "__v":0}]
But it is...
[{"_id":"5d76a7e78b55cd3309b91ecf","__v":0}]
Sorry figured it out myself. Form was outputting fields that weren't in the model. Changed form to...
<form id="add-form" method="POST" action="/makepost">
<label for="post_title">Title</label>
<input type="text" name="post_title">
<!-- <label for="post_category">Category</label>
<select name="post_category">
<option>Coding</option>
<option>Music</option>
<option>Books</option>
<option>Other Stuff</option>
</select> -->
<label for="post_date">Content</label>
<input type="date" name="post_date">
<label for="post_content">Content</label>
<input type="text" name="post_content">
<input type="submit">
</form>
Basically just changed the names of input fields to match the model.
While in / view, I get documents from mongodb and create a list item for each document that only shows the date and the first few words. I want to be able to click on each list item to go to a new page, /view, to see the rest of that particular document.
To do this, I believe I need to pass item between / and /view, then access the properties of item there. How do I do this with the pagelist function (or without it)?
index.js:
var express = require('express');
var exphbs = require('express-handlebars');
var bodyParser = require('body-parser');
var app = express();
var hbs = exphbs.create({
helpers: {
message: function() {return 'Welcome!';},
doc: function() {return "Something went wrong.";}
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var util=require('util');
const url = 'mongodb://localhost:27017/users';
const dbName = 'users';
var db;
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
db.collection("reviewYelp2", { }, function(err, coll) {
if (err != null) {
console.log(err)
db.createCollection("reviewYelp2", function(err, result) {
assert.equal(null, err);
});
}
db.ensureIndex("reviewYelp2", { document: "text"}, function(err, indexname) {
assert.equal(null, err);
});
});
});
app.get("/", function(req, res) {
res.render('search');
});
app.get("/view", function(req, res) {
// NEED TO BE ABLE TO ACCESS CLICKED ITEM HERE
res.render('viewItem', {
// Change to access item.text when I have access to item
helpers: {
doc: function() {return "Viewing doc...";}
}
});
});
app.post("/", function(req, res) {
db.collection('reviewYelp2').find({
text: new RegExp(req.body.query)
}).sort({date: 1}).toArray(function(err, items) {
res.render('search', {
helpers: {
message: function() {return pagelist(items);}
}
});
})
});
function pagelist(items) {
result = "<ul>";
items.forEach(function(item) {
// Grab only first 10 words of text
textSlice = item.text.split(" ");
textSlice = textSlice.slice(0, 5);
text = textSlice.join(" ");
str = "<li class="+item._id+"><a href='/view'>" + item.date + " " + text + "...</a></li>";
result = result + str;
});
result = result + "</ul>";
return result;
}
app.listen(3000, function() {
console.log("App listening on localhost:3000");
});
search.handlebars:
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="text" size="80" name="query" />
<input type="submit" value="Search" class="submitButton" />
{{{ message }}}
</form>
</body>
</html>
viewItem.handlebars:
<!DOCTYPE html>
<html>
<body>
<button onclick="window.history.back()">Go back to list</button>
{{{ doc }}}
</body>
</html>
This is problematic because http is fundamentally stateless — that is each request to the server is it's own thing. You can come up with schemes involving cookies or local storage, but I think a simpler approach is both better and more common.
A simpler idea is to have a route that takes some sort of id parameter:
app.get("/view_detail/:itemID", function(req, res) {
var item = req.params.itemID
// lookup detail about item based on itemID
res.render('viewItem', {
// send data
});
});
Now on index you can have a list of links that look like :
/view/878743 (or whatever scheme you have for db keys)
/view/36764e
I'm trying to setup a simple login page using express framework , mongodb and passport for authentication.
My authentication always goes to the failstate. Where am I wrong ?
my sever.js:
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
//var router = express.Router();
var path = require('path');
var mongoose = require('mongoose');
var User = require('./model');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(username, password, done) {
users.findOne({
username : 'username'
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
}
));
app.post('/login',
passport.authenticate('local', { failureRedirect: '/error' }),
function(req, res) {
res.redirect('/success?username='+req.user.username);
});
//app.use("/",router);
//app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));//ALWAYS LAND HERE
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
/*passport.deserializeUser(function(id, cb) {
User.findById(id, function(err, user) {
cb(err, user);
});
});
*/
//app engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
mongoose.connect('mongodb://localhost:27017/UserSchema');
/*
router.use(function (req,res,next) {
console.log("/" + req.method);
next();
});*/
app.get("/",function(req,res){
res.render('index');
});
app.post("/user",function (req, res) {
var u = new User();
//console.log(req.body);
u.email = req.body.email;
u.name = req.body.name;
u.password = req.body.password;
//p.photo = req.body.photo;
u.save(function (err) {
if (err) {
res.send(err);
}
res.render('login');
});
});
app.get("/login",function (req, res) {
res.render('login');
});
app.get("/all",function (req, res) {
User.find(function (err, products) {
if (err) {
res.send(err);
}
res.send(products);
});
});
/*
router.get("/about",function(req,res){
res.sendFile(path + "about.html");
});
router.get("/contact",function(req,res){
res.sendFile(path + "contact.html");
});
app.use("*",function(req,res){
res.sendFile(path + "404.html");
});
*/
app.listen(3000,function(){
console.log("Live at Port 3000");
});
sorry for the junk comments
here is my mongoose schema (model.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: String,
name: String,
password: String,
//photo: String,
});
module.exports = mongoose.model('User', UserSchema);
my login.ejs :
<!DOCTYPE html>
<html>
<<title>Login</title>
<body>
<form action="/login", method="post">
Email:<br>
<input type="text" name="username">
<br>
Password:
<br>
<input type="text" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and my registration page which is able to register and insert in db:
<!DOCTYPE html>
<html>
<body>
<form action="/user", method="post">
Email:<br>
<input type="text" name="email">
<br>
Name:<br>
<input type="text" name="name" >
<br>
Password:
<br>
<input type="text" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
<a href="/login"/><input type="submit" value="Login">
</body>
</html>
You imported your MongoDB User model as:
var User = require('./model');
However, you are calling the .findOne() method on "users"
passport.use(new LocalStrategy(
function(username, password, done) {
users.findOne({
username : 'username'
}, function(err, user) {
Should it not be User.findOne()
If that doesn't resolve the issue then you should elaborate more on what you mean by "my application always go to the failstate".
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}`);
})