Mongodb not working with Nodejs - node.js

I'm trying to print name and job of people after taking input from via a html form on the browser. The program also allows deletion and update of record through simple links on the same page. The program is, however, not working.
I even tried creating a "newapp" database (created in the server file) and filled it with some dummy values, the program still wont work!
Following is my node.js file
var express= require("express"),
http= require("http"),
bodyparser= require('body-parser'),
mongo= require("mongodb");
var app= express(),
db= new mongo.Db("newapp",
new mongo.Server("localhost", 27017),
{safe:true}, {auto_reconnect: true}),
people= db.collection("people");
app.use(bodyparser.urlencoded({extended: true}));
app.get("/", function(req, res){
people.find().toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
app.listen(3000);
My index.jade file is:
form(method="POST")
p Name:
input(type="text", name="name")
p Job:
input(type="text", name="job")
p: button Add
if(typeof(people)!=="undefined")
ul
each person in people
li
h2= person.name+ " ("+ person.job+ ")"
p
a(href="/update/#{person._id}") Update
a(href="/delete/#{person._id}") Delete
else
p No People
Any help is much appreciated. Thanks a lot!

The error was that I had not done db.open(...) anywhere in the program
Correct working code is:
var express= require("express"),
http= require("http"),
bodyparser= require("body-parser"),
mongo= require("mongodb");
var app= express(),
db= new mongo.Db("newapp", new mongo.Server("localhost", "27017"),
{safe:true}, {auto_reconnect: true});
app.use(bodyparser.urlencoded({extended: true}));
db.open(function(err, db){
if(err)
console.log(err);
people= db.collection("people");
app.get("/", function(req, res){
var cursor= people.find();
cursor.toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
app.get("/update/:id", function(req, res){
people.findOne({_id: new mongo.ObjectID(req.params.id)},
function(err, doc){
if(err)
throw err;
res.render("update.jade", {person: doc});
});
});
app.post("/update/:id", function(req, res){
people.update({_id: new mongo.ObjectID(req.params.id)},{
name: req.body.name,
job: req.body.job
}, function(err, item){
if(err)
throw err;
res.redirect("/");
});
});
app.get("/delete/:id", function(req, res){
people.remove({_id: new mongo.ObjectID(req.params.id)},
function(err){
if(err)
throw err;
res.redirect("/");
});
});
});
app.listen(3000, function(){
console.log("Now Listening on port: 3000");
});
The index.jade (in views folder) is:
form(method="POST")
p Name:
input(type="text", name="name")
p Job:
input(type="text", name="job")
p: button Add
if(people!==NULL)
ul
each person in people
li
h2= person.name+ " ("+ person.job+ ")"
p
a(href="/update/#{person._id}") Update&nbsp
a(href="/delete/#{person._id}") Delete
else
p No People
The update.js (in views folder) is:
form(method="POST")
p Name:
input(type="text", name="name", value="#{person.name}")
p Job:
input(type="text", name="job", value="#{person.job}")
p: button Update

please check this hope this will work..
var express= require("express"),
http= require("http"),
bodyparser= require('body-parser'),
var MongoClient = require('mongodb').MongoClient;
var connect = require('connect'),
var app= express(),
MongoClient.connect("mongodb://localhost:27017/newapp", function(err, db) {
if(err) { return console.dir(err); }
var people = db.collection('people');
app.use(bodyparser.urlencoded({extended: true}));
app.get("/", function(req, res){
people.find().toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
});
app.listen(3000);

Related

How to fix 'Parsing error: Unexpected token' in Node?

On saving the code (Node JS), getting the error, 'Parsing error: Unexpected Token'
Note - Mongo connected
Tried adjusting the curly brackets and semicolon, still not working
What am I doing wrong?
Below is the code,
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
//connecting and creating a database
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//schema setup
var campgroundSchema = new mongoose.Schema({
name: String,
url: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create( {name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
function(err, campground){
if (err){
console.log(err);
}
else {
console.log("newly created campground");
console.log(campground);
}
});
var campgrounds = [
{name: "Jenny Lake", image:"https://farm2.staticflickr.com/1424/1430198323_c26451b047.jpg"},
{name: "RichardBH", image:"https://photosforclass.com/download/flickr-7626464792"},
{name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
{name: "CampAliBabaHai", image:"https://photosforclass.com/download/flickr-2770447094"},
{name: "CampAliBabaHaiYe", image:"https://photosforclass.com/download/flickr-2602356334"},
];
app.get("/", function(req, res){
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
app.post("/campgrounds", function(req, res){
var name = req.body.name
var image = req.body.image
var newcampground = {name: name, image: image}
campgrounds.push(newcampground);
res.redirect("/campgrounds");
});
app.get("/campgrounds/new" , function(req, res){
res.render("new.ejs");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("YelpCamp server started!");
});
Expected-
The file should save error-free in order to start the server and run the application
Actual-
Getting above mentioned error
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});// missing the closing brackets
});
you have miss the closing tag
On line 55, you should have an extra });
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
});

Why are documents not being deleted from the mongodb database?

I'm trying to delete a document form the mongodb database but it isn't working. I don't understand why because the console doesn't give any errors and displays the query object properly. However, when I view the database the respective document is still there.
URL
http://localhost:7000/delete/5c641f44923cf17c1cfe1002
Console
{ _id: '5c641f44923cf17c1cfe1002' }
1 document deleted
Server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
const MongoClient = require('mongodb').MongoClient;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Connection URL
const url = "mongodb://localhost:27017/DataBaseName";
app.listen(7000);
app.set('view engine', 'ejs');
// Express routes
//Default routes
app.get('/', function(req, res){
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("DataBaseName");
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(db);
db.close();
res.render('index', {result:result});
});
});
});
//Submit button route
app.post('/submitData',urlencodedParser,function(req, res){
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("DataBaseName");
dbo.collection("customers").insertOne(req.body, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
res.redirect("/");
});
// var _mongodb = require('mongodb');
// var ObjectId = mongodb.ObjectId;
app.get('/delete/:id', function (req, res) {
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("DataBaseName");
dbo.collection("customers").deleteOne({_id: new ObjectId(req.params.id) }, function(err, res) {
if (err) throw err;
// console.log({_id: req.params.id});
console.log("1 document deleted");
db.close();
});
});
res.redirect("/");
});
// Catch all other routes
app.get('*',function(req, res){
res.send("You lost Niqqa!");
});
An entry in the database
This is what it looks like in mongodb compass community.
_id:ObjectId("5c641f44923cf17c1cfe1002")
name:"Please delete me"
priority:"high"
You should convert the id from the request to ObjectId as it's passed now as string which won't match the document.
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;
app.get('/delete/:id', function (req, res) {
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("DataBaseName");
dbo.collection("customers").deleteOne({_id: new ObjectId(req.params.id) }, function(err, res) {
if (err) throw err;
console.log({_id: req.params.id});
console.log("1 document deleted");
db.close();
});
});
res.redirect("/");
You can also check the res from the delete operation to know whether any documents where deleted or not. The res should have deletedCount based on mongodb node driver docs.

GET /signup - - ms - -(both get and post not working, it was a while idk whats wrong)

1.GET /signup - - ms - -(both GET and POST not working, it was a while I don’t know whats wrong)
2. please check below code
3.server.js. This this the app code that you have requested.Kindly go through it. Also the value for link is replaced by word link as it is private.
4. There are two files in this. Server.js and user.js kindly check it out.
var router = require("express").Router();
var User = require("../models/user.js");
router.get("/signup", function(req, res){
res.send("hello");
});
router.post('/signup', function(req, res, next){
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne( { email : req.body.email }, function(err, existingUser) {
if(existingUser){
console.log(req.body.email + "already exists");
return res.redirect("/signup");
}
else{
user.save(function(err, user){
if(err) return next(err);
res.send("New user has been added");
});
}
});
});
module.exports = router;
//server.js code
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var User = require("./models/user.js");
var ejs = require("ejs");
var engine = require("ejs-mate");
var app = express();
mongoose.connect('link', function(err){
if(err){
console.log(err);
}
else{
console.log("connected to database");
}
});
//middle ware
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.engine("ejs", engine);
app.set("view engine", "ejs");
var mainRoutes = require("./routes/main.js");
var userRoutes = require("./routes/user.js");
app.use(mainRoutes,function(err){
if(err){
console.log("error is here")
}
});
app.use(userRoutes, function(err){
if(err){
console.log("error is here in 2" );
}
});
//listen to port 3000
app.listen(3000, function(err){
if(err) throw err;
console.log("Server has started");
});
removed the call back function from app.use() and it worked.

CRUD express.JS with mysql issue

I have this as configuration of my Express index.js:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var router = express.Router();
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'learn'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
router.get('/add', function (req, res, next){
res.render('add_costumer', {title: 'Update'});
});
router.post('/add', function (req, res){
var input = req.body;
var data = {
name : input.name,
email : input.email,
phone : input.number_phone
};
connection.query('INSERT INTO `test` SET ?', data, function(err,rows){
if(err) throw err;
console.log("Error inserting : %s ",err );
res.redirect('/');
});
});
router.get('/update', function (req, res, next){
res.render('update', {judul: 'Add'});
});
module.exports = router;
But still when I ask for req.body.something in my routes I get some error pointing Cannot read property 'name' of undefined. Here is an example of a route that uses req.body and this picture of the printing code :
output like this
Any clue?
It looks like you are requiring body-parser but not actually using it.
Depending on what kind of content you are accepting you should do:
app.use(bodyParser.json()); // where app is your express app
app.use(bodyParser.urlencoded({ extended: true});

Cannot POST (Commenting on a post) | Mongodb with mongoose

I'm building an app in NodeJS/Express combined with Mongodb, where I want to be able to comment to a post but I keep getting a 404 not found.
I setup the models and routes in my server.js and also setup the 'ref' between the two but this is the response I keep getting:
And as you can see with the following, the 'capture' aka 'post' does actually exist:
Edit: Made some changes to my initial code with the answers that Zen gave me.
This is my code:
-server.js
// Init Express Web Framework
var express = require('express');
var app = express();
var path = require('path');
// Set view engine to EJS & set views directory
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, 'client', 'views'));
app.use(express.static(path.resolve(__dirname, 'client')));
// Database Connection
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
require('./server/routes/capture');
require('./server/routes/comment');
mongoose.connect(configDB.url);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: 'application/json'}));
// Main route
app.get('/', function(req, res){
res.render('index.html');
});
// API
var api = express.Router();
require('./server/routes/capture')(api);
require('./server/routes/comment')(api);
app.use('/api', api);
// Port Settings
app.listen(process.env.PORT || 3000, process.env.IP);
console.log('Listening on port ' + process.env.PORT);
-capture.js model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = Schema({
birdname: {type: String, required: true},
place: String,
userId: String,
author: String,
picture: Schema.Types.Mixed,
created_at: Date,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});
module.exports = mongoose.model('Capture', captureSchema);
-capture.js route:
var Capture = require('../models/capture');
module.exports = function(router) {
router.post('/captures', function(req, res){
var capture = new Capture();
capture.birdname = req.body.birdname;
capture.place = req.body.place;
capture.userId = req.body.userId;
capture.author = req.body.author;
capture.picture = req.body.picture;
capture.created_at = new Date();
capture.save(function(err, data){
if(err)
throw err;
console.log(req.body);
res.json(data);
});
});
router.get('/captures', function(req, res){
Capture.find({}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures', function(req, res){
Capture.remove({}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
router.get('/captures/:id', function(req, res){
Capture.findOne({_id: req.params.id}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures/:id', function(req, res){
Capture.remove({_id: req.params.id}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
};
-capture.js model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = Schema({
birdname: String,
body: {type: String, required: true},
userId: {type: String, required: true},
author: {type: String, required: true},
created_at: Date,
capture: [{ type: Schema.Types.ObjectId, ref: 'Capture'}]
});
module.exports = mongoose.model('Comment', commentSchema);
-comment.js route:
var Comment = require('../models/comment');
module.exports = function(router) {
router.post('/captures/:capture/comments', function(req, res, next){
var comment = new Comment();
comment.birdname = req.body.birdname;
comment.body = req.body.body;
comment.userId = req.body.userId;
comment.author = req.body.author;
comment.created_at = new Date();
comment.capture = capture;
comment.save(function(err, comment) {
if (err) { return next(err); }
req.capture.comments.push(comment);
req.capture.save(function(err, capture) {
if (err) { return next(err); }
res.json(comment);
});
});
});
};
Any help is much appreciated..
Thanks
I would work with one route script, seeing that your comments are attached to the post.
You also have to add a Map logic to the route parameters for cature and comment.
Try the following:
var Capture = require('../models/capture');
var Comment = require('../models/comment');
module.exports = function(router) {
router.post('/captures', function(req, res){
var capture = new Capture();
capture.birdname = req.body.birdname;
capture.place = req.body.place;
capture.userId = req.body.userId;
capture.author = req.body.author;
capture.picture = req.body.picture;
capture.created_at = new Date();
capture.save(function(err, data){
if(err)
throw err;
console.log(req.body);
res.json(data);
});
});
router.get('/captures', function(req, res){
Capture.find({}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures', function(req, res){
Capture.remove({}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
// Map logic to route parameter 'capture'
router.param('capture', function(req, res, next, id) {
var query = Capture.findById(id);
query.exec(function (err, capture) {
if (err) { return next(err); }
if (!capture) { return next(new Error("can't find post")); }
req.capture = capture;
return next();
});
});
// Map logic to route parameter 'comment'
router.param('comment', function (req, res, next, id) {
var query = Comment.findById(id);
query.exec(function (err, comment) {
if (err) { return next(err); }
if (!comment) { return next(new Error("can't find comment")); }
req.comment = comment;
return next();
});
});
router.get('/captures/:id', function(req, res){
Capture.findOne({_id: req.params.id}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures/:id', function(req, res){
Capture.remove({_id: req.params.id}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
router.post('/captures/:capture/comments', function(req, res, next){
var comment = new Comment();
comment.birdname = req.body.birdname;
comment.body = req.body.body;
comment.userId = req.body.userId;
comment.author = req.body.author;
comment.created_at = new Date();
comment.capture = req.capture;
comment.save(function(err, comment) {
if (err) { return next(err); }
req.capture.comments.push(comment);
req.capture.save(function(err, capture) {
if (err) { return next(err); }
res.json(comment);
});
});
});
};
The status code is 404. Apparently, no corresponding router is found. The problem is that you export an "init" function in comment.js route. When you require the comment router in server.js, nothing happens.
// API
var api = express.Router();
require('./server/routes/capture')(api);
// you have forgotten it
require('./server/routes/comment')(api);
app.use('/api', api);
BTW, there is no need putting capture into req.body when you're posting to '/captures/:capture/comments', since you can get :capture by using const capture = req.params.capture;.

Resources