i'm building a web page for a library with node and mongoose in atom. I've created a log in form, register and an "add book". Now in the home page i want to see all the books and i dont know to to do that. I know it way have something to do with double {{}} or triple {{{}}} brackets but I'm not sure. I will put it later in a prettyer form, for now i just want to see how I can print, for example the titles. Btw i'm using the handlebars view engine.
<h2 class="page-header">Cartile existente</h2>
<h4>In curand!</h4> // <- there I'm supposed to put the book titles.
<h2 class="page-header">Adauga o carte noua</h2>//this is the "add a book"
{{#if errors}}
{{#each errors}}
<div class="alert alert-danger">{{msg}}</div>
{{/each}}
{{/if}}
<form method="post" action="/booksImp/addbook">
<div class="form-group">
<label>Numar Inventar</label>
<input type="text" class="form-control" placeholder="Numar curent" name="nrinv">
</div>
<div class="form-group">
<label>Titlu</label>
<input type="text" class="form-control" placeholder="Titlu" name="titlu">
</div>
<div class="form-group">
<label>Autor</label>
<input type="text" class="form-control" placeholder="Autor" name="autor">
</div>
<div class="form-group">
<label>Editura</label>
<input type="text" class="form-control" placeholder="Editura, Locul publicatiei" name="editura">
</div>
<div class="form-group">
<label>An</label>
<input type="text" class="form-control" placeholder="An publicatie" name="an">
</div>
<div class="form-group">
<label>Pret</label>
<input type="text" class="form-control" placeholder="Pret" name="pret">
</div>
<button type="submit" class="btn btn-success">Trimite</button>
</form>
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var BookSchema = mongoose.Schema({
nrinv: {
type: String,
index: true
},
titlu: {
type: String
},
autor: {
type: String
},
editura: {
type: String
},
an: {
type: String
},
pret: {
type: String
}
});
var Book = module.exports = mongoose.model('bookImp', BookSchema);
module.exports.getBooks = (callback, limit) => {
Book.find(callback).limit(limit);
}
module.exports.getBookById = (id, callback) => {
Book.findById(id, callback);
}
module.exports.addBook = (book, callback) => {
Book.create(book, callback);
}
module.exports.removeBook = (id, callback) => {
var query = {
_id: id
};
BookImp.remove(query, callback);
}
var express = require('express'); //this is the controller code =))))
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Book = require('../models/bookImp');
router.get('/addbook', ensureAuthenticated, function(req, res, next) {
res.render('addbook');
});
router.post('/addbook', function(req, res, next) {
var nrinv = req.body.nrinv;
var titlu = req.body.titlu;
var autor = req.body.autor;
var editura = req.body.editura;
var an = req.body.an;
var pret = req.body.pret;
//console.log(name);
req.checkBody('nrinv', 'Introduceti numarul de inventar').notEmpty();
req.checkBody('titlu', 'Introduceti titlul').notEmpty();
req.checkBody('autor', 'Introduceti autorul').notEmpty();
req.checkBody('editura', 'Introduceti editura si locul').notEmpty();
req.checkBody('an', 'Introduceti anul').notEmpty();
// req.checkBody('an', 'Introduceti anul').isnumber();
req.checkBody('pret', 'Introduceti pretul').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('addbook', {
errors: errors
});
} else {
var newBook = new Book({
nrinv: nrinv,
titlu: titlu,
autor: autor,
editura: editura,
an: an,
pret: pret
});
Book.addBook(newBook, function(err, book) {
if (err) throw err;
console.log(book);
});
req.flash('success_msg', 'Ati adaugat o carte cu succes');
res.redirect('/booksImp/addbook');
}
});
router.post('/addbook',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/booksImp/addbook',
failureFlash: true
}),
function(req, res) {
res.redirect('/');
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
//req.flash('error_msg', 'Trebuie sa va logati');
res.redirect('/users/login');
}
}
module.exports = router;
var express = require('express');
var router = express.Router();
var Book = require('../models/bookImp');
router.get('/', ensureAuthenticated, function(req, res, next) {
res.render('index');
});
router.get('/api/books', ensureAuthenticated, function(req, res) {
Book.getBooks(function(err, books) {
if (err) {
throw err;
}
res.json(books);
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
//req.flash('error_msg', 'Trebuie sa va logati');
res.redirect('/users/login');
}
}
module.exports = router;
Related
I'm developing an application with Node.js and EJS but there is an error. It says "msg_type is not defined". When I'm using handlebars, there is no problem. What is my mistake. Actually, when url goes to /auth/login , the message is displaying but it's not displaying in /login routing.
my users.js file (controllers)
exports.login = async (req, res,next) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).render("login", {
msg: "Kullanıcı Adınız veya Parolanız Hatalı",
msg_type: "error",
},
next()
);
}
await login_db.query(
"select * from users where email=?",
[email],
async (error, result) => {
console.log(result);
if (result.length <= 0) {
return res.status(401).render("login", {
msg: "E-mailiniz veya Parolanız Hatalı",
msg_type: "error",
});
} else {
if (!(await bcrypt.compare(password, result[0].PASS))) {
return res.status(401).render("login", {
msg: "E-mailiniz veya Parolanız Hatalı",
msg_type: "error",
});
} else {
const id = result[0].ID;
const token = jwt.sign({ id: id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
console.log("The Token is " + token);
const cookieOptions = {
expires: new Date(
Date.now() +
process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true,
};
res.cookie("joes", token, cookieOptions);
res.status(200).redirect("/anasayfa");
}
}
}
);
} catch (error) {
console.log(error);
}
};
my auth.js file
const express = require("express");
const userController = require("../controllers/users");
const router = express.Router();
router.post("/login", userController.login);
my login.ejs file
<% if (true) { %>
<p class="<%= msg_type %>"><%= msg %> </p>
<% } %>
<form action="/auth/login" method="post">
<div class="data">
<label for="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div class="data">
<label for="password">Şifre</label>
<input type="password" name="password" id="password" />
</div>
<div class="forgot-pass">
Şifrenizi mi unuttunuz?
</div>
<div class="btn">
<button type="submit">Giriş Yap</button>
</div>
<div class="signup-link">
Kayıtlı değil misin? Şimdi Kayıt Ol!
</div>
</form>
my app.js file
app.use("/", require("./routes/pages"));
app.use("/auth", require("./routes/auth"))
;
my pages.js file
router.get(["/", "/login"], (req, res) => {
//res.send("<h1>Hello Tutor Joes Salem</h1>");
res.render("login");
});
The variable should be exported from the original file(users.js) and also should be imported in login.ejs, so you can use it without problems, this is how things work in Javascript.
I am learning javascript and databases, so I am practicing by making a todo list application. Which add item dynamically in the lists. List is created through URL like http://localhost:3000/work creates a work list, but whenever I try to add something it shows an error.
my JS code:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true, useUnifiedTopology: true });
const itemsSchema = {
name: String
};
const Item = mongoose.model ("Item", itemsSchema);
const item1 = new Item ({
name: "item1"
});
const item2 = new Item ({
name: "item2"
});
const item3 = new Item ({
name: "item3"
});
const defaultItems = [item1, item2, item3];
const listSchema = {
name: String,
items: [itemsSchema]
};
const List = mongoose.model("List", listSchema);
app.get("/", function(req, res) {
Item.find({}, function(err, foundItems){
if(foundItems.length === 0){
Item.insertMany(defaultItems, function(err){
if(err){
console.log(err);
} else {
console.log("Succesfully saved the items");
}
});
res.redirect("/");
} else {
res.render("list", {listTitle: "Today", newListItems: foundItems});
}
});
});
app.get("/:customListName", function(req, res){
const customListName = req.params.customListName;
List.findOne({name: customListName}, function(err, foundList){
if(!err){
if(!foundList){
//Create a new list
const list = new List({
name: customListName,
items: defaultItems
});
list.save();
res.redirect("/" + customListName);
} else{
//show the existing list
res.render("list", {listTitle: foundList.name, newListItems: foundList.items})
}
}
});
});
app.post("/", function(req, res){
const itemName = req.body.newItem;
const listName = req.body.list;
const item = new Item ({
name: itemName
});
if(listName === "Today"){
item.save();
res.redirect("/");
} else {
List.findOne({name: listName}, function(err, foundList){
if(err){
console.log(err);
} else{
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
}
});
}
});
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
Item.findByIdAndRemove(checkedItemId, function(err){
if(!err){
console.log("Succesfully deleted the item!!");
res.redirect("/");
}
});
});
app.get("/about", function(req, res){
res.render("about");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
My ejs code:
<%- include("header") -%>
<div class="box" id="heading">
<h1> <%= listTitle %> </h1>
</div>
<div class="box">
<% newListItems.forEach(function(item) { %>
<form action="/delete" method="post">
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
<p><%=item.name%></p>
</div>
</form>
<% }); %>
<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button type="submit" name="list" value="<%=listTitle%>">+</button>
</form>
</div>
<%- include("footer") -%>
The List.findOne function might return either one "List" { name: String, items: [itemsSchema]} item or null. Unfortunately, you don't check for the null condition which can happen if this list hasn't been created yet in your database.
To solve this issue, you'll need to add an existence check for the foundList variable in your code.
If the foundList variable isn't null, then the foundList contains a list and a new item can be pushed to it.
Else if the foundList variable is null, you can create a new list with this name and the item you want to add to it.
if (err) {
console.log(err);
} else if (foundList !== null) {
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
} else {
// List is not found, here you can create a new list with the item, or possibly return an error to the user (listName not found!)
foundList = new List({ foundList: [item], name: listName });
foundList.save();
res.redirect("/" + listName);
}
PS: You could refactor the code I wrote above to reduce duplication.
This is my first Stackoverflow post, i'll try to make it simple. I have to build a social network with the mean stack for my school. Pretty amazingg technology but i can't find how to use properly the function population of mongoose for linking comments to posts. My comments are saved in the database but appared in all the posts on my first page. Can you tell me what i done wrong ? Thanks in advance !
Here's my view post
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form ng-submit="pst.sendPost()">
<div class="form-group">
<label for="text">Your post</label>
<input type="text" class="form-control" id="text" placeholder="share your thoughts..." ng-model="pst.newpst.text">
</div>
<button type="submit" class="btn btn-default">Post</button>
</form><br>
<div ng-repeat="post in pst.posts | orderBy: '-'">
<div class="well">{{post.text}}
<br><form ng-submit="pst.sendComment(post._id)">
<br><div class="well">
<label for="comment"></label>
<input type="text" class="form-control" id="comment" placeholder="comment..." ng-model="pst.newcmt.text">
</div>
<div ng-repeat="comment in pst.comments| orderBy: '+'" class="alert alert-info" role="alert">{{comment.text}}<br>{{comment._id}}
<button class="btn btn-primary" type="button" ng-click="pst.removeComment(comment._id)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</form>
<button class="btn btn-primary" type="button" ng-click="pst.removePost(post._id)">Remove Post</button>
</div>
</div>
</body>
</html>
Here's my angular controller
angular.module('app')
.controller('PostController', function($scope, $http) {
var _this = this;
this.getPosts = function() {
$http.get('/api/posts')
.then(function(res){
_this.posts = res.data;
});
};
this.getPosts();
this.removePost = function(id) {
$http.delete('/api/posts/' + id)
.then(function(){
_this.getPosts();
});
};
this.sendPost = function() {
if (!this.newpst || !this.newpst.text)
return;
$http.post('api/posts', this.newpst)
.then(function(){
_this.getPosts();
});
this.newpst = {};
};
this.updatePost = function(id) {
$http.post('/api/posts/' + id)
.then(function(){
_this.getPosts();
});
};
this.getComments = function() {
$http.get('/api/comments')
.then(function(res){
_this.comments = res.data;
});
};
this.getComments();
this.removeComment = function(id) {
console.log(id);
$http.delete('/api/comments/' + id)
.then(function(){
_this.getComments();
});
};
this.sendComment = function(id) {
this.newcmt.post = id
console.log(this.newcmt)
$http.post('api/comments', this.newcmt)
.then(function(){
_this.getComments();
});
this.newcmt = {};
};
this.updateComment = function(id) {
$http.post('/api/comments/' + id)
.then(function(){
_this.getComments();
});
};
})
Here's my post.model.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Post', {
text: {
type: String,
default: ''
},
image: {
type: String,
default: ''
},
comment1: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
});
my routes_posts.js
var Post = require('./post.model');
module.exports = function(app) {
app.delete('/api/posts/:id', function(req, res) {
Post.remove({_id: req.params.id}, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
app.get('/api/posts', function(req, res) {
Post.find({})
.populate('comment')
.exec(function(err, posts){
(err ? console.log(err) : res.json(posts))
})
});
app.post('/api/posts', function(req, res) {
Post.create(req.body, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
};
my comment.model.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Comment', {
text: {
type: String,
default: ''
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
}
});
my routes_comment.js
var Comment = require('./comment.model');
var Post = require('../posts/post.model')
module.exports = function(app) {
app.get('/api/comments', function(req, res) {
Post.find({})
.populate('post_id')
.exec(function(err, comments){
(err ? console.log(err) : res.json(comments))
})
});
app.post('/api/comments', function(req, res) {
console.log(req)
Comment.create(req.body, function( err) {
(err ? res.send(err) : res.status(200).send());
});
});
app.delete('/api/comments/:id', function(req, res) {
Comment.remove({_id: req.params.id}, function(err) {
(err ? res.send(err) : res.status(200).send());
});
});
};
Thanks !
I need your help. I want to make User registration form and use Nodejs, Express.js, MongoDB(mongoose) and give me very simple example how to make user registration form with: Name, Email, Password and Mobile Number :) I've made mongoose schema and give values like that Name: req.body.name but it won't work :/ In my oppinion I made something bad.
this is my code and if you think it's not correct, please correct it. (sorry for my bad english). this is server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/addressbookdb');
var express = require('express');
var app = express();
var db = mongoose.connection;
app.use(express.static(__dirname + '/../client'));
app.post("/",function(req,res){
res.end("Registration Succesfully Completed!");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("connected.")
});
// Schema
var RegSchema = mongoose.Schema({
Name: String,
Email: String,
Pass: String,
Num: Number,
reg_time : {
type : Date, default: Date.now
}
}, { collection: 'AddressCol' });
// Model
var UserReg = mongoose.model('UserReg', RegSchema);
// Add in collection
var UserAdd = new UserReg({
Name: req.body.name,
Email: req.body.email,
Pass: req.body.pass,
Num: req.body.num,
});
// Save
UserAdd.save(function (err, fluffy) {
if (err) return console.error(err);
});
});
app.listen(8000, function() {
console.log("Server is running!");
});
and this is my HTML page:
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="name><br>
<input type="email" class="form-control" id="email" placeholder="Email"><br>
<input type="password" class="form-control" id="pass" placeholder="Password"><br>
<input type="number" class="form-control" id="num" placeholder="Number"><br>
<button type="submit" class="btn btn-primary" id="reg-form-btn">Registration!</button>
</div>
<script>
$(document).ready(function() {
$("#reg-form-btn").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var pass = $("#pass").val();
var num = $("#num").val();
$.post("/", {
Name: name,
Email: email,
Pass: pass,
Num: num
});
});
});
</script>
Maybe you should consider Passport or another module.
But you can do something like this:
app.post('/signup', function (req, res, next) {
var user = {
Name: req.body.name,
Email: req.body.email,
Pass: req.body.pass,
Num: req.body.num
};
var UserReg = mongoose.model('UserReg', RegSchema);
UserReg.create(user, function(err, newUser) {
if(err) return next(err);
req.session.user = email;
return res.send('Logged In!');
});
});
app.post('/login', function (req, res, next) {
var email = req.body.email;
var pass = req.body.pass;
User.findOne({Email: email, Pass: pass}, function(err, user) {
if(err) return next(err);
if(!user) return res.send('Not logged in!');
req.session.user = email;
return res.send('Logged In!);
});
});
app.get('/logout', function (req, res) {
req.session.user = null;
});
Then you should have a middleware to handle authentication
function isLoggedIn (req, res, next) {
if (!(req.session && req.session.user)) {
return res.send('Not logged in!');
}
next();
}
And use it on the private routes
app.get("/api", isLoggedIn, function (req, res) {
//Something private
})
Here is a nice tutorial how to make what you want using very useful module passport. Also you will have a quick look at Jade template engine which can be useful in your further learning of creating express apps.
check this tutorial...you can ignore Angular and mongojs if you want:
http://www.phloxblog.in/single-page-application-angular-js-node-js-mongodb-mongojs-module/#.Vc20OXW1Gkq
You are missing body-parser. Try this in your server code:
const bodyParser = require('body-parser');
app.use(bodyParser);
Please refer the question How to access the request body when POSTing using Node.js and Express?
I am running into an issue where my POST route from a form submissions redirects correctly without any issues, but none of the information is passed on to a document in database. I am not sure the best way to debug this issue.
blogpost-create.ejs
<html>
<head>
<% include ../partials/head %>
<script src="//cdn.ckeditor.com/4.4.5/standard/ckeditor.js"></script>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid grid-pad">
<div class="col-1-1">
<h1>Blog Create</h1>
<form action="/admin/posts/create" method="POST">
Title: <input type="text" name="title"><br>
Author:
<select name="author">
<option value="Author">Author</option>
</select><br>
Category:
<select name="category">
<option value="Analytics/SEO/SEM">Analytics/SEO/SEM</option>
<option value="Advice">Advice</option>
<option value="Programming">Programming</option>
<option value="Thoughts">Thoughts</option>
</select><br>
Tagline: <input type="text" maxlength="160" name="tagline"><br>
Content:<br>
<textarea name="content" id="blog-editor" rows="10" cols="80">
Text editor.
</textarea><br>
Tags: <input type="text" name="tags"><br>
<input type="submit" value="Submit">
</form>
</div>
</div>
<script>
// Replace the <textarea id="blog-editor"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'blog-editor' );
</script>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
routes.js
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(function(req, res) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
title: params.blogpost_title
};
}
function getBlogpostUpdate(body) {
return {
title: body.title,
author: body.author,
tagline: body.tagline,
content: body.content,
category: body.category,
tags: body.tags
};
}
var blogpostsRoute = router.route('/blog/:blogpost_title');
// to manipulate your route params, use router.param
router.param('blogpost_title', function (req, res, next, blogpost_title) {
req.param.blogpost_title = blogpost_title.toLowerCase();
next();
});
blogpostsRoute
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
module.exports = router;
blogModel.js
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: String, lowercase: true },
date: { type: Date, default: Date.now }
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
Your form is missing content (currently you have the name as blog-editor), author, and category fields (the last two are the <select>s but they're missing names and their <option>s are missing value attributes. Other than that you have maxlength:"160" which should probably be maxlength="160".