I´ve just started learning NodeJS to use as a back-end of my applications, but this is my first time working with a server-side technology.
I am trying to build a simple app which is a form where I want to insert the data into the database (mongodb) and get the data to display on the front end. I am using express-handlebars.
The data is successfully being saved into the database, however when I am trying to get the data from the database to display on the front end nothing happens.
Does anyone knows what may be wrong with my code ?
Thank you!!
//code begins here
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var assert = require('assert');
var url = 'mongodb://felipe:teste#ds033125.mlab.com:33125/form';
mongoose.connect(url);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
// INSERT DATA INTO DATABASE(MONGODB)
router.post('/insert', function(req, res, next) {
var Schema = mongoose.Schema;
var itemSchema = new Schema({
nome: String,
sobrenome: String,
nacionalidade: String,
email: String
});
var CreateItem = mongoose.model('CreateItem', itemSchema);
var item = new CreateItem({
nome: req.body.getNome,
sobrenome: req.body.getSobrenome,
nacionalidade: req.body.getNacionalidade,
email: req.body.getEmail
});
item.save(function(err) {
if (err) throw err;
console.log(item.nome + ' was saved!');
});
res.redirect('/');
console.log(item.nome + ' ' + item.sobrenome + ' was saved!');
});
// GET DATA FROM MONGODB AND DISPLAY ON THE FRONT END
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongoose.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('createitems').find();
cursor.forEach(function(err, doc) {
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close;
res.render('index', {items: resultArray});
});
});
res.redirect('/');
});
// HTML where the data will be displayed
{{# each items}}
<tr>
<div class="col-md-3">
<td class="data">{{ this.nome }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.sobrenome }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.nacionalidade }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.email }}</td>
</div>
</tr>
{{/each}}
do not use this: {{ this.nome }}
just use it like that: {{ nome }}
Take reference from this example, i have created one route which you can access at (http://localhost:3000/test) you need to start the express server before accessing this route, This route will get the data from mongo db using mongoose and will return it. You can try this route using postman.
var express = require("express"),
app = express(),
bodyparser = require("body-parser"),
mongoose = require("mongoose");
const router = express.Router();
app.use(bodyparser.json());
mongoose.connect('mongodb://localhost:27017/test');
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB connected successfully');
})
var schema = new mongoose.Schema({
name: String,
value: String
})
var data=mongoose.model("testdata", schema);
router.route('/test').get((req, res) => {
data.find((err, (testdata);=> {
if (err)
console.log("Found some error" + err)
else
res.json(testdata);
})
})
app.use('/', router);
app.listen(3000, function () {
console.log('server started on port 3000');
});
Related
I am trying to do my first API Rest and I am following some tutorials. I am requesting all the articles in a MongoDB database.
This is the code of the main:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require('mongoose');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
// Import Models and controllers
var models = require('./models/article')(app, mongoose);
var articleCtrl = require('./controllers/articleController');
// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
articles.route('/articles/:id')
.get(articleCtrl.findById);
articles.route('/articles')
.get(articleCtrl.findAllarticles)
.post(articleCtrl.addarticle);
app.use('/api', articles);
app.use(router);
mongoose.connect('mongodb://localhost/ustcg', { useNewUrlParser: true ,useUnifiedTopology: true}, function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
The code of the controller is here:
// Import article and mongoose
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
//GET - Return a article with specified ID
exports.findById = function(req, res) {
Article.findById(req.params.id, function(err, Article) {
if(err) return res.send(500, err.message);
console.log('GET /article/' + req.params.id);
res.status(200).jsonp(Article);
});
};
//GET - Return all articles in the DB
exports.findAllarticles = function(req, res) {
Article.find(function(err, Article) {
if(err) res.send(500, err.message);
console.log('GET /article')
res.status(200).jsonp(Article);
});
};
//POST - Insert a new article in the DB
exports.addarticle = function(req, res) {
console.log('POST');
console.log(req.body);
var Article = new Article({
title: req.body.title,
paragraphs: req.body.paragraphs
});
Article.save(function(err, Article) {
if(err) return res.send(500, err.message);
res.status(200).jsonp(Article);
});
};
The model:
//We create the model
exports = module.exports = function(app, mongoose) {
var ArticleSchema = new mongoose.Schema({
title: { type: String },
paragraphs: { type: Array },
});
mongoose.model('Article', ArticleSchema);
};
When I tried to request the following http request it send me 404 error. I can not see any logs on the console so it is not entering the methods in order to see the exception is happening so I am stucked with this...
If someone could help me it would be nice.
what is articles variable in your main file.
I tried your code in my machine and struggled with articles variable and you have extra imports which are not required.
Try following code it works fine
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var articleCtrl = require('./sample.controller');
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
router.get('/articles/:id', articleCtrl.findById);
router.post('/articles', articleCtrl.addarticle);
router.get('/articles', articleCtrl.findAllarticles)
// app.use('/api', router);
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
if you uncomment app.use('/api', router); then you can also use routes as localhost:3000/api/articles
i am currently trying node & express. The Project is a small Movie Library. Today i tryed to implement a search for titles of movies, the problem i have is when i submit my form and get my query String like this http://localhost:3000/movies/?title=Hustlers i get all the Data in my Database. But when i manually type the Url like this http://localhost:3000/movies/title=Hustlers it works fine and i get the matching result. I tryed change my Routes but i am stuck right now.
here is the movies.js
const express = require("express");
const router = express.Router();
const Movie = require("../models/movie");
//Get Back all the movies
router.get("/", async (req, res) => {
try {
const movies = await Movie.find();
res.json(movies);
} catch (err) {
res.json({ message: err });
}
});
//specific Movie
router.get("/title=:title", async (req, res) => {
try {
const movie = await Movie.find({ title: req.params.title });
res.json(movie);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
my app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
//Middlewares
app.use(bodyParser.json());
app.use(cors());
app.use(express.urlencoded());
const moviesRoute = require("./routes/movies");
app.use("/movies", moviesRoute);
app.use(express.static(__dirname + "/"));
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true });
app.listen(3000);
and my submit form here
<form action="/movies/">
<input type="text" name="title" />
<input
type="submit"
value="Suchen"
class="btn btn-primary btnNewMovie"
/>
</form>
The = is messing it up, because that character is reserved for the query component. It would also look much cleaner as /title/movie_title. Try this:
router.get("/title/:title", async (req, res) => {
try {
const movie = await Movie.find({ title: req.params.title });
res.json(movie);
} catch (err) {
res.json({ message: err });
}
});
There's a difference between query string params and route params.
When you submit a form, normally it will encode the request as application/x-www-form-urlencoded (More info here), then the express router parse those values and provide them thru the query hash. For more information on how to properly use the route params on express go here and read the Route parameters section.
I am a begginer at node.js and trying to build a basic todo list but keep getting the error:
Cannot read property 'collection' of undefined.
Can someone please explain what im doing wrong and how to I can get my get post requests working?
Thanks for the help !
routes/index.js
var express = require('express');
var router = express.Router();
var ObjectId = require('mongodb').ObjectId
// Get Homepage
router.get('/', ensureAuthenticated, function(req, res){
req.db.collection('Todo').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('index', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('index', {
title: 'User List',
data: 'ldld'
})
}
})
})
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
routes/Todo.js
// list dependencies
var express = require('express');
var router = express.Router();
// add db & model dependencies
var mongoose = require('mongoose');
var Todo = require('../models/Todo');
// interpret GET /products - show product listing */
// GET intepret GET /products/edit/:id - show single product edit form */
router.get('/Todo/edit/:id', function (req, res, next) {
//store the id from the url in a variable
var id = req.params.id;
var user_id = req.cookies ?
req.cookies.user_id : undefined;
//use the product model to look up the product with this id
Todo.findById(id,user_id, function (err, product) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.render('edit', { Todo: Todo });
}
});
});
// POST /products/edit/:id - update selected product */
router.post('/Todo/edit/:id', function (req, res, next) {
var id = req.body.id;
var Todo = {
_id: req.body.id,
content: req.body.content,
todos : todos,
updated_at : Date.now()
};
Todo.update({ _id: id}, content, function(err) {
if (err) {
res.send('Product ' + req.body.id + ' not updated. Error: ' + err);
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// GET /products/add - show product input form
router.get('/Todo/create', function (req, res, next) {
res.render('add');
});
// POST /products/add - save new product
router.post('/Todo/create', function (req, res, next) {
// use the Product model to insert a new product
Todo.create({
content: req.body.content,
user_id:req.cookies.user_id,
updated_at : Date.now()
}, function (err,Todo) {
if (err) {
console.log(err);
res.render('error', { error: err }) ;
}
else {
console.log('Product saved ' + Todo);
res.render('added', {Todo: Todo.content });
}
});
});
// API GET products request handler
router.get('/api/Todo', function (req, res, next) {
Todo.find(function (err, products) {
if (err) {
res.send(err);
}
else {
res.send(Todo);
}
});
});
/* GET product delete request - : indicates id is a variable */
router.get('/Todo/delete/:id', function (req, res, next) {
//store the id from the url into a variable
var id = req.params.id;
//use our product model to delete
Todo.remove({ _id: id }, function (err,Todo) {
if (err) {
res.send('Product ' + id + ' not found');
}
else {
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + '/Todo');
res.end();
}
});
});
// make controller public
module.exports = router;
views/index.handelbars
<h2 class="page-header">Dashboard</h2>
<p> Hello {{user.name}}
<p>Welcome to your dashboard</p>
<% layout( 'layout' ) -%>
<h1 id="page-title">{{ title }}</h1>
<div id="list">
<form action="/create" method="post" accept-charset="utf-8">
<div class="item-new">
<input class="input" type="text" name="content" />
</div>
</form>
{{#each todo}}
<div class="item">
<a class="update-link" href="/edit/{{#todo._id }}" title="Update this todo item">{{todo.content}}</a>
<a class="del-btn" href="/destroy/{{ #todo._id }}>" title="Delete this todo item">Delete</a>
</div>
{{/each }}
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var Todo = require('./routes/Todo');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/Todo', Todo);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Add the following to your app.js, right after var app = express();
app.use(function (req, res, next) {
req.db = db;
next();
});
This will create a reference to your mongoose connection in all the incoming requests, accessible via req.db.
Guys I'm going through a udemy class on Node and Express and I've gotten stuck. I'm implementing a route using a GET method ruest. The route has the form of "campgrounds/:id" however, there's a route above that has the name of "/campgrounds/new" which is submission form. here's the link to working web app.
and the webpage of working app
http://webdevcamp-miatech.c9users.io/campgrounds
when you click on any of the buttons "more info" it will redirect to "campgrounds/:id" for now I"m just testing the route and I'm printing some text.
app.js file
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
//connect mongoose db
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true})); //parsing html request
app.set("view engine", "ejs"); //handling vies through ejs pages
//schema/model for data to be inserted in db
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
})
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create({
name: "Salmon Creek",
image: "https://farm6.staticflickr.com/5786/20607281024_5c7b3635cc.jpg",
description: "This is a huge granite hill, no bathroom campground"
}, function(err, campground) {
if(err) {
console.log(err);
}
else {
console.log("Created Campground");
console.log(campground);
}
})
//default route
app.get("/", function(req, res) {
res.render("landing");
})
app.get("/campgrounds", function(req, res) {
Campground.find({}, function(err, allCampgrounds) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {campgrounds: allCampgrounds});
}
})
});
//method to add to database and redirect to campgrounds
app.post("/campgrounds", function(req, res) {
// res.send("you hit post route");
//get data from form and add to campgrounds array
var name = req.body.name;
var imgUrl = req.body.image;
var newCampGround = {name: name, image: imgUrl};
//adding to database table
Campground.create(newCampGround, function(err, newlyCreated) {
if(err) {
console.log(err);
}
else {
res.redirect("/campgrounds");
console.log(newlyCreated);
}
});
});
app.get("/campgrounds/new", function(req, res) {
res.render("new.ejs");
})
//displaying especific campground
app.get("campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
//starting server
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started!..");
});
Here's my project on c9.io
https://ide.c9.io/miatech/webdevcamp
missing slash before campgrounds
app.get("/campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
router.post('/login', function(req, res) {
console.log("processing");
res.send('respond with a resource');
});
module.exports = router;
And here is the code I am using to stored POST data into my mongoDB database. This is located in my app.js file...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
var Schema = mongoose.Schema;
db.on('error', console.error);
db.once('open', function() {
console.log("connected");
var Schema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('emp', Schema);
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Code works fine up until it reaches the app.post, after that it does not seem to read the rest of the code.
I know my index.js file works because when I submit the form, I get to a page that displays respond with a resource (because of the send function). But for some reason, app.post is not being read, am I missing something?
Here is my jade html to show that I am implementing everything correctly...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
input(type="submit",name = "homePage" class ="loginButton" value="Log In" id="loginButton")
Please try to move the following code out of db.once('open')
db.on('error', console.error);
db.once('open', function() {});
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Another issue in your code, please make sure the first parameter of mongoose.model is User, otherwise, one error could pop up.
var UserSchema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('User', UserSchema);