Why are documents not being deleted from the mongodb database? - node.js

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.

Related

Using mongoDB how can i prevent someone from using the same username as someone else?

I have a form where a user is supposed to put in there nickname, the issue is I need the nickname to be unique, in that no one else should be able to make there nickname the same as someone elses. Is there a fix for this using only mongoDB and not mongoose?
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var PORT = 3332;
app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost/gtra", {
useNewUrlParser: true
});
var db = mongoose.connection;
db.once("open", function(cb) {
console.log("connection established");
});
app.post("/addname", (req, res) => {
var name = req.body.pickname;
var data = {
nickname: name
};
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
});
app.listen(PORT, function() {
console.log("server is up and running using port " + PORT);
});
You can check if there is already a username in the collection, if exists you can throw exception.
app.post("/addname", (req, res) => {
var data = {
nickname: req.body.pickname
};
db.collection("dat").findOne({ nickname: data.nickname }, function(err, doc) {
if (err) throw err;
if (doc) {
return res.status(400).send("Nickname already taken"); //or throw whatever you want
} else {
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
}
});
});
Another option is creating a unique index on the nickname field.
db.users.createIndex( { "nickname": 1 }, { unique: true } )
Change users to your collection name.

how to redirect to another page from a node.js server

i have been struggling for the pas few days i want to redirect to another page from my node.js server.
first by website is redirecting me to my server to do a task but when that task is done i want the server to redirect me back to my website.
here is the node js server code.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var urlQuery = url.parse(req.url, true).query;
removeItem(urlQuery.itemToRemove);
addItem(urlQuery.itemToAdd);
**// i have been trying to redirect to my html site **
**// i have got a error saying TypeError: res.redirect is not a function**
res.redirect('index.html');
res.end();
}).listen(8080);
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = {
itemName: remove
};
dbo.collection("shoppingCart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
console.log("deleted:" + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = {
itemName: create
};
dbo.collection("shoppingCart").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("document inserted:" + myobj);
db.close();
});
});
}
}
You are getting that error because response.redirect() is an express function and your app is based purely on nodejs http library.
You can accomplish what you have mentioned this way:
res.writeHead(301,{Location: 'your-location'});
res.end();
You are not creating the server properly. Try to keep your code clean,Write separate API for serving index.html, not inside creating the server.
TypeError: res.redirect is not a function
This is because res.redirect is an express function and you're using plain http node server.
You can consider using express for handling redirects for you.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost:27017/';
// express
const express = require('express');
const app = express();
const port = 8080;
// for templating
// create `views/` folder
// and place `index.pug` and `redirected-page.pug`
app.set('view engine', 'pug');
app.get('/redirect', (req, res) => {
res.render('redirected-page');
});
app.get('/', (req, res) => {
var urlQuery = url.parse(req.url, true).query;
Promise.all([
removeItem(urlQuery.itemToRemove),
addItem(urlQuery.itemToAdd),
]).then(() => {
res.redirect('redirect');
});
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
function removeItem(remove) {
if (remove !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myquery = {
itemName: remove,
};
dbo.collection('shoppingCart').deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log('deleted:' + myquery);
db.close();
});
});
}
}
function addItem(create) {
if (create !== undefined) {
MongoClient.connect(mongourl, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
var myobj = {
itemName: create,
};
dbo.collection('shoppingCart').insertOne(myobj, function(err, res) {
if (err) throw err;
console.log('document inserted:' + myobj);
db.close();
});
});
}
}
app.listen(port, () => console.log(`Server is running at ${port}!`));

Cannot post membership/login/submit

I have some code to create an account and have a login page and say true or false if you entered the correct details but instead it says 'Cannot post /membership/login/submit'.
my main.js code (the html files are basic and the forms are just standard tags with an action and a method, tell me if you want these)
var app = require('express')();
var http = require('http').Server(app);
var httpuse = require('http');
var io = require('socket.io')(http);
var MongoClient = require('mongodb').MongoClient;
var users = require(__dirname + '/local_js/users.js');
var public = __dirname + "/www/";
var bodyParser = require('body-parser')
var url = "mongodb://localhost:27017/";
const bcrypt = require('bcrypt');
var needle = require('needle');
const saltRounds = 10;
app.use(bodyParser.urlencoded({ extended: false }));
function rand(n) {
Math.floor(Math.random() * (n+1));
}
function getToken(hashedpass, user) {
return hashedpass+"_._"+user;
}
app.get('/', function(req, res){
res.sendFile(public + 'index.html');
});
app.get('/membership/create/form', function(req, res){
res.sendFile(public + 'user/create.html');
});
app.post('/membership/create/submit', function(req, res){
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
if (err) {throw err;}
var newUser = { nickname: req.body.nickname, password: hash };
dbo.collection("users").insertOne(newUser, function(errd, ress) {
if (errd) throw errd;
console.log("1 user document inserted");
db.close();
res.send("200 OK");
});
});
});
});
app.get('/membership/login/form', function(req, res) {
res.sendFile(public + 'user/login.html');
});
app.post('membership/login/submit', function(req, res) {
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
dbo.collection("users").findOne({nickname: req.body.nickname}, function(err, result) {
if (err) throw err;
if (result) {
bcrypt.compare(req.body.password, result.password, function(err, ress) {
console.log(ress);
res.send(ress);
});
}
});
db.close();
});
});
// IGNORE THIS
app.post('api/v1/getSessionValid', function(req, res) {
let token = req.body.token;
let userInfo = token.split('_._');
if (userInfo[0] && userInfo[1]) {
}
});
io.on('connection', function(socket){
console.log('connection');
socket.on('disconnect', function(){
console.log("disconnection");
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
it says 'Cannot post /membership/login/submit'.
Don't forget the / at the beginning of your route.
// Try this
app.post('/membership/login/submit', ...)
// Instead of
app.post('membership/login/submit', ...)

Express.js nested routes without parameters

I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};

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