Mongodb not showing my Aggregation - node.js

I am currently having trouble with showing my aggregation records. I wanted to show the summed up value for all the documents but its not showing. It keeps showing me the Records not found only. I don't know where i have gone wrong. Someone help me out.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('meibanlist', ['contact']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/meibanlist', function (req, res) {
console.log('I received a GET request');
db.meibanlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/meibanlist', function (req, res) {
console.log(req.body);
db.meibanlist.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/meibanlist/', function (req, res) {
console.log();
db.meibanlist.remove(function (err, doc) {
res.json(doc);
});
});
app.get('/meibanlist/', function (req, res) {
console.log();
db.meibanlist.findOne(function (err, doc) {
res.json(doc);
});
});
app.put('/meibanlist/', function (req, res) {
console.log(req.body.machine_Id);
db.meibanlist.findAndModify({
query: {_id: mongojs.machine_Id},
update: {$set: {machine_Id: req.body.machine_Id, air_Temp: req.body.air_Temp, water_Temp: req.body.water_Temp, heat_Temp: req.body.heat_Temp, room_Temp: req.body.room_Temp, date:req.body.date, time: req.body.time}},
new: true}, function (err, doc) {
res.json(doc);
}
);
});
db.contact.aggregate([{$group: {machine_Id : "$machine_Id", air_Temp : {$sum : "$likes"}}}], function(err, meibanlist) {
if( err || !meibanlist ) console.log("Record not found");
else meibanlist.forEach (function(machine_Id){
console.log(machine_Id);
});
});
app.listen(3000);
console.log("Server running on port 3000");

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.

Invalid Input syntax for Integer postgresql error

I am trying to run the delete query from app.js file to postgresql database but every time I am getting error: invalid input syntax for integer: "undefined"
Below is my app.js file code:
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cons = require('consolidate'),
dust = require('dustjs-helpers'),
pg = require('pg-promise'),
pgdb = require('pg'),
app = express();
//DB Connection
const config = {
user: 'Nasreen',
database: 'Inventory1',
password: 'test',
port: 5432 //Default port, change it if needed
};
const pool = new pgdb.Pool(config);
//assign dust engine
app.engine('dust', cons.dust);
//set default ext
app.set('view engine', 'dust');
app.set('views', __dirname + '/views');
//set public folder
app.use(express.static(path.join(__dirname, 'public')));
//Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('SELECT * FROM "Products"', function (err, result) {
if (err) {
return console.error('error running query', err);
}
res.render('index', { Products: result.rows });
done();
});
});
});
app.post('/add', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('INSERT INTO "Products" ("Name", "Purchase_Qty", "Purchase_Rate") VALUES($1, $2, $3)',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate]);
done();
res.redirect('/');
});
});
app.delete('/delete/:ID', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('DELETE FROM "Products" WHERE "ID" = $1',
[req.params.ID]);
done();
res.sendStatus(200);
});
});
app.post('/edit', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('UPDATE "Products" SET "Name"= $1, "Purchase_Qty"= $2, "Purchase_Rate"= $3 WHERE "ID"= $4',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate, req.body.ID]);
done();
res.redirect('/');
});
})
INSERT is working fine with double quotes for column names and table name but delete and edit wont't work.
Can someone plz help!!
You don't need to quote the tables' names and the columns' names.
Change the delete statement to:
"DELETE FROM Products WHERE ID = '$1'";
Change the update statement to:
"UPDATE Products SET Name= '$1', Purchase_Qty= '$2', Purchase_Rate= '$3' WHERE ID= '$4'";
EDIT:
Try this:
client.query(`DELETE FROM "Products" WHERE "ID" = ${req.params.ID}`);
It's a function overloading for query. Using template string should solve the issue.
Instead of:
client.query('DELETE FROM "Products" WHERE "ID" = $1',[req.params.ID]);

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', ...)

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.

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);
});
};

Resources