Button for remove a object in mongoDB - javascript

Sorry for my bad english.
I have a problem. I need to create, for all object in my mongoDB, a delete button for each object.
I use mongodb, Nodejs, ajax and jquery.
This is my mongodb code :
{
"_id" : ObjectId("57ce990ac4e8ec94124a1c2c"),
"Pseudo" : "shade",
"Commentaire" : "blabla",
"Note" : "2",
"Date" : ISODate("2016-09-06T10:22:53.257Z")
}
{
"_id" : ObjectId("57cebf1c12253ee41e0aa53e"),
"Pseudo" : "shade2",
"Commentaire" : "blablaalalalallala",
"Note" : "5",
"Date" : ISODate("2016-09-06T13:00:10.871Z")
}
{
"_id" : ObjectId("57d7b7b909087b981124bc42"),
"Pseudo" : "shade3",
"Commentaire" : "hfsduhfdiugfusqdigfqgfugsufgsfqd",
"Note" : "1",
"Date" : ISODate("2016-09-13T07:45:24.970Z")
}
My node code :
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017/jeux';
var myDate = new Date;
app.use(express.static(__dirname + '/fichiers'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/fichiers'))
app.get('/', function (req, res) {
res.render('index.html');
})
app.get('/api/affiche', function (req,res){
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
db.collection('temp').find().toArray(function (err, result) {
if (err) {
throw err;
} else {
res.json(result);
}
});
}
});
})
var server = app.listen(8080, function () {
var adressHost = server.address().address;
var portHost = server.address().port;
console.log('Ecoute à l\'adresse http://%s:%s', adressHost, portHost);
});
My jade code
doctype html(lang='fr')
head
meta(charset='utf-8')
script(type='text/javascript', src='jquery.js')
script(type='text/javascript', src='admin.js')
link(rel='stylesheet', href='admin.css')
body
h1 Page d'admin
.listeAvis
And my jquery/ajax code
$(function () {
$.ajax({
type: 'GET',
url: '/api/affiche',
success: function (data) {
$('.liste').html('<h2>Nouveaux avis</h2>');
for (var i = 0; i < data.length; i++) {
//var i = 0;
$('.listeAvis').append('<p>pseudo : ' + data[i].Pseudo + '</p>');
$('.listeAvis').append('<p>commentaire : ' + data[i].Commentaire + '</p>');
$('.listeAvis').append('<p>note : ' + data[i].Note + '</p>');
$('.listeAvis').append('<p>-----------------------------</p>');
$('.listeAvis').append('<br></br>');
}
}
})
})
I thought but I can not find how to do. Please help me :(

Related

how to get formated JSON data from node.js server?

I wrote code to get the data from HTML page (client) to server.js (node.js) and it will save JSON file locally.
This is my server.js :
var http = require('http');
var util = require('util')
var fs = require('fs');
http.createServer(function (req, res) {
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
fs.writeFile("./text1.json", JSON.stringify(body, null, 4), (err) => {
if (err) {
console.error(err);
return;
}
console.log("File has been created");
});
});
req.on('end', function () {
console.log("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html','Access-Control-Allow-Origin': '*'});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}
else
{
console.log("GET");
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}
}).listen(8090);
console.log('Server running on port 8090');
and Here my HTML code from where I am sending data :
data_frame = {
"frame": i,
"Objects_classname" : obj.getObjects()[1].text,
"x_val":obj.left,
"y_val":obj.top,
"width":obj.width,
"height" : obj.height
}
$.ajax({
url: 'http://127.0.0.1:8090',
// dataType: "jsonp",
data: data_frame,
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = JSON.parse(JSON.stringify(data));
//$('#layer1').html(ret.msg);
//console.log(ret);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
// $('#layer1').html('Error connecting to the server.');
},
});
});
So the output I am getting is like this in JSON file :
"output%5Bframe%5D=11&output%5BObjects_classname%5D=car2&output%5Bx_val%5D=518.94958&output%5By_val%5D=130.03093&output%5Bwidth%5D=65.58593999999994&output%5Bheight%5D=104.8877"height%5D=213.56171"
but I wants this format :
var data = [
{
"Frame_count":1,
output:[
{
"Objects_classname":"car1",
"x_val":82.9883,
"y_val":197.56245,
"width":316.03088,
"height":197.45451
},
{
"Objects_classname":"car2",
"x_val":522.4823,
"y_val":170.47263,
"width":64.66687,
"height":61.78085
},
],
"Total_objects_detected":2,
},
{
"Frame_count":2,
output:[
{
"Objects_classname":"car1",
"x_val":78.9991,
"y_val":189.48058,
"width":327.41028,
"height":198.80226
}
],
"Total_objects_detected":1,
}]
SO how can i achieve this.
I tried with jsonstringify(body, null, 4) but this is not working.
Try this as your server:
let express = require('express'),
fs = require('fs'),
bodyParser = require('body-parser'),
app = express(),
port = process.env.PORT || process.argv[2] || 8080;
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/', function (req, res) {
console.log(req.body);
fs.writeFile("./text1.json", JSON.stringify(req.body, undefined, 4), (err) => {
if (err) {
console.error(err);
res.send(err);
}
console.log("File has been created");
res.json(req.body);
});
});
app.listen(port, function () {
console.log('body-parser demo is up on port: ' + port);
});
This is you index.html file put it in same folder as your server.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript">
var data_frame = {
"Objects_classname": "car1",
"x_val": 82.9883,
"y_val": 197.56245,
"width": 316.03088,
"height": 197.45451
};
$.ajax({
url: '/',
data: JSON.stringify(data_frame),
type: 'POST',
contentType: 'Application/json',
success: function(data) {
var ret = JSON.parse(JSON.stringify(data));
console.log('Success: ')
},
error: function(xhr, status, error) {
console.log('Error: ' + error.message);
}
});
</script>
<body>
</body>
</html>

Middleware getting executed multiple times?

I am trying to make a url shortener app using express. I have 2 middle wares for routes /shorten/:url* and /:code respectively. Somehow when I make requests like /shorten/iamarshad.com (requests that are not formatted and will fail my validateUrl method), middleware handling that request gets executed sometimes twice and sometime thrice. Why is this happening ?
Code for route.js:
var express = require("express");
var router = express.Router();
var crypto = require("./crypto");
var styles = "<style>#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond');" +
"body{background: #fefefe; word-wrap: break-word;}" +
"p {font-size: 30px;color: #b33c66;font-family: 'Cormorant Garamond', monospace;text-align: center;" +
"margin-top: 40vh;font-weight: 500;word-spacing: 2px;}</style>";
function verifyUrl(req, res, next) {
console.log("/shorten middleware called");
req.params.url += req.params[0];
console.log(req.params.url);
if (validateUrl(req.params.url)) {
req.db.collection("counter")
.find({_id: "counter"})
.toArray(function (err, docs) {
if (err) console.error("Error occurred while getting COUNTER document:", err);
req.encodedId = crypto.encode(docs[0].count);
next();
});
}
else {
var elem = "<p>Please enter correct and formatted url!</p>";
res.send(styles + elem);
}
}
function incrementCounter(req, res, next) {
// increasing counter
req.db.collection("counter")
.update(
{
_id: "counter"
},
{
$inc : {
count : 1
}
}
);
next();
}
function insertUrlDocument(req, res, next) {
//inserting new url document
var obj = {original_url: req.params.url, _id: req.encodedId, entry_time: new Date().toUTCString()};
req.db.collection("urls")
.insert(obj, function(err, data) {
if(err) console.error("Error happened while adding new document:", err);
});
next();
}
function sendResponse(req, res) {
var elem = "<p>" + JSON.stringify({'original_url': req.params.url, 'short_url': 'https://shorten-that.herokuapp.com/' + req.encodedId}) + "</p>";
res.send(styles + elem);
}
function validateUrl(url) {
var format = /(http:\/\/|https:\/\/)[a-z0-9\-]+[.]\w+/;
return (format.test(url));
}
router.get("/:code", function(req, res) {
console.log("/:code middleware called with url", req.params.code);
var code = req.params.code.toString();
// searching short-url-id
req.db.collection("urls")
.find({_id: code})
.toArray(function(err, docs) {
if(err) console.error("Error occurred while searching urls:", err);
console.log(docs);
if(docs.length > 0)
res.redirect(docs[0]["original_url"]);
else {
var elem = "<p>Oops, wrong url requested!</p>";
res.send(styles + elem);
}
});
});
// better solution needed
router.get("/shorten/:url*", [verifyUrl, incrementCounter, insertUrlDocument, sendResponse]);
module.exports = router;
Code for server.js:
var express = require("express")
, mongo = require("mongodb").MongoClient
, port = process.env.PORT || 8080
, path = require("path")
, routes = require("./routes")
, favicon = require("serve-favicon");
var app = express();
app.use(favicon(path.join(__dirname, 'public','favicon.png')));
app.use(express.static(path.join(__dirname, "public")));
var url = 'mongodb://localhost:27017/url-shortener';
mongo.connect(url, function(err, db) {
if (err) console.error("Error occurred while connecting to db:", err);
console.log("successfully connected to db.");
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
});
app.listen(port, function() {
console.log("App running on", port);
});

Node & Mongo db.open giving undefined is not a function

Following this tutorial, when running my server.js file I am getting the following error
self.s.pool = new Pool(Object.^assign(self.s.options, options, {bson:this.s.
TypeError: undefined is not a function
"
Seems to be a problem with my db.open() function. However, I am unsure as to whether it is because a connection can not be made to the database or something else.
I can log the server and db objects, so not sure where the undefined error is coming from. It doesn't log the error message contained in the db.open function so something seems to break before then.
Any help would be great, below is my code
server.js
var express = require('express'),
movies = require('./routes/movies.js');
var app = express();
app.configure(function(){
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
app.get('/movies',movies.findAll);
app.get('/movies/:id',movies.findById);
app.post('/movies', movies.addMovie);
app.put('/movies/:id',movies.updateMovie);
app.delete('/movies/:id',movies.deleteMovie);
app.listen(3000);
console.log('Listening on port 3000...');
routes/movies.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('moviedb', server);
db.open(function(err,db){
if(!err)
{
console.log('Connected to "moviesdb" database');
db.collection('movies',{strict:true},function(err,collection){
if(err)
{
console.log("The 'movies' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findAll = function(req,res){
db.collection('movies',function(err,collection){
collection.find().toArray(function(err,items){
res.send(items);
});
});
}
exports.findById = function(req,res){
var id = req.params.id;
console.log('Retrieving movie: ' + id);
db.collection('movies',function(err,collection){
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err,item){
res.send(item);
});
});
}
exports.addMovie = function(req,res){
var movie = req.body;
console.log('Adding movie: ' + JSON.stringify(movie));
db.collection('movies',function(err,collection){
collection.insert(movie,{'safe':true},function(err,result){
if(err)
{
res.send({'error':'An error has occurred'});
}
else
{
console.log('Success:' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
exports.updateMovie = function(req,res){
var id = req.params.id,
movie = req.body;
console.log('Updating movie: ' + id);
console.log(JSON.stringify(movie));
db.collection('movies',function(err,collection){
collection.update({'_id':new BSON.ObjectID(id)},movie,{'safe':true},function(err,result){
if(err)
{
console.log('Error updating movie: ' + err);
res.send({'error':'An error has occured'});
}
else
{
console.log('' + result + ' document(s) updated');
res.send(movie);
}
});
});
}
exports.deleteMovie = function(req,res){
var id = req.params.id;
console.log('Deleting movie: ' + id);
db.collection('movies',function(err,collection){
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
if(err)
{
res.send({'error':'An error has occurred - ' + err});
}
else
{
console.log('' + result + ' document(s) deleted');
res.send(req.body);
}
});
});
}
/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
var populateDB = function() {
var movies = [
{
name: "Titanic",
release: "2009",
description: "description....",
picture: "titanic-poster.jpg"
},
{
name: "Jaws",
release: "2000",
description: "description....",
picture: "jaws-poster.jpg"
},
{
name: "Halloween",
release: "1992",
description: "description....",
picture: "halloween-poster.jpg"
}
];
db.collection('movies', function(err, collection) {
collection.insert(movies, {safe:true}, function(err, result) {});
});
}

updating mongodb using new json object

im trying to update my mongodb using a new json object i got from the browser but the update method doesnt do anything (i also tried to use updateOne and it still didnt work).
my server code:
var express = require("express");
var path = require("path");
var url = require("url");
var app = express(); // express.createServer();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname));
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
var insertMsg, Collection;
var socketMap = {};
MongoClient.connect('mongodb://127.0.0.1:27017/EladGuy', function(err, db) {
if(err)
throw err;
Collection = db.collection('messages');
console.log("connected to DB");
insertMsg = function (saveJson) {
console.log("Start Saving...");
db.collection('messages').insertOne(saveJson);
console.log("Finish saving successfuly...");
};
removeMessages = function(msg, callback) {
db.collection('messages').deleteMany(
{ "name": msg },
function(err, results) {
console.log(results);
callback();
}
);
};
updateMessage = function(msg,callback) {
db.collection('messages').updateOne({"name":msg.name},{$set: msg},function(err, results) {
console.log(msg.name);
console.log(results);
callback();
});
};
});
app.get("/TestUpdate", function(request, response) {
var screenId = request.query.id;
console.log("Updating station number: " + screenId);
var newMsg = {
"screensId":[parseInt(screenId)],
"name":"msg6",
"text":["Won the lottary?","Want to invest your money?","Shulberg investment company","Your money is important to us!"],
"images":["http://thefilipinoexpat.com/wp-content/uploads/2015/11/04_investment.jpg"],
"template":"/html/templateA.html",
"msgTime":5000,
"timeFrame":[
{ "startDate" : [2016,0,1], "endDate" : [2016,11,31], "days" : [0,1,2,3,4,5,6], "startTime" : 6, "endTime" : 23},
{ "startDate" : [2016,0,1], "endDate" : [2016,11,31], "days" : [5], "startTime" : 13, "endTime" : 20}] }
insertMsg(newMsg);
if (socketMap[parseInt(screenId)] != undefined) {
socketMap[parseInt(screenId)].emit('messageUpdate', newMsg);
}
response.send("SUCCESS!");
});
app.get("/screen=:screenNum", function(request, response) {
response.sendFile(__dirname + '/station/station.html');
});
app.get("/html/:template", function(request, response) {
var template = request.params.template;
response.sendFile(__dirname + '/station/' + template);
});
app.get("/stationPreview=:screenNum", function(request, response) {
response.sendFile(__dirname + '/station/stationPreview.html');
});
app.get("/*", function(request, response) {
response.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('sendId', function(stationId) {
socketMap[parseInt(stationId)] = socket;
});
socket.on('getMessagesByScreen', function(screenId) {
res = [];
Collection.find({"screensId":{'$eq': parseInt(screenId)}}).toArray(function(err, docs) {
docs.forEach(function(doc) {
res.push(doc);
});
socket.emit('sendMessages', res);
});
});
socket.on('getAllMessages',function(unUsed) {
res = [];
Collection.find().toArray(function(err, docs) {
docs.forEach(function(doc) {
res.push(doc);
});
socket.emit('sendAllMessages', res);
});
});
socket.on('deleteMessage', function(msg) {
removeMessages(msg, function() {
socket.emit('DeleteSuccessed', null);
});
});
socket.on('getMessage', function(msg) {
Msg = [];
Collection.find({"name":{'$eq': msg}}).toArray(function(err, docs) {
docs.forEach(function(doc) {
Msg.push(doc);
});
socket.emit('sendMessage', Msg);
});
});
socket.on('getStations', function(unUsed) {
Collection.distinct("screensId", function(err, stationsArray) {
socket.emit('sendStations', stationsArray);
});
});
socket.on('EditMessage', function(update){
updateMessage(update,function(){
console.log("UPDATE SUCEES!!!");
});
});
});
server.listen(8080, function() {
console.log("Messages Application Express node js server listening on port %d...", this.address().port);
});
as you may see in my socket im using:"on('EditMessage')" when this happening the server activate the function:"updateMessage" which gets the update which is a json object just like the other ones stored in the mongodb.
my update should find the name of the message (which is uniq to each message) and update the message.
when i do so i get on console from the undifined and the the message "UPDATE SUCCESS" and when i check again i see that it didnt do anything.

how to get json response using js file

Hi I am developing android application for that I am using request.js by using the below files how to get the json array and by using this json array I can parse the json object then i will use the server response in clent.
Can any help me.
package.json
{
"name": "node-chat",
"version": "0.0.1",
"main": "app.js",
"dependencies": {
"express" : "~4.0.0",
"mysql" : "~2.5.3",
"connect": "~2.14.4",
"request": "2.36.0"
}
}
app.js
/**
* Module dependencies.
*/
var express = require('express');
var connect = require('connect');
var app = express();
var port = process.env.PORT || 8080;
// Configuration
app.use(express.static(__dirname + '/public'));
app.use(connect.logger('dev'));
app.use(connect.json());
app.use(connect.urlencoded());
// Routes
require('./routes/routes.js')(app);
app.listen(port);
console.log('The App runs on port ' + port);
request.js
var request = require('request');
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'chat',
}
);
connection.connect();
exports.login = function(name,mobno,reg_id,callback) {
var data = {
name : name,
mobno : mobno,
reg_id : reg_id
};
var que = "SELECT * from users WHERE mobno =" + mobno;
var query = connection.query(que, function(err, rows)
{
if(rows.length == 0){
var query = connection.query("INSERT INTO users set ? ",data, function(err, rows)
{
callback({'response':"Sucessfully Registered"});
});
}else {
callback({'response':"User already Registered"});
}
});
}
exports.getuser = function(mobno,callback) {
var query = connection.query("SELECT * from users", function(err, rows)
{
if(rows.length == 0){
callback({'response':"No Users Registered"});
}else {
callback(removeUser(rows, mobno));
}
});
}
exports.removeuser = function(mobno,callback) {
var que = "DELETE FROM users WHERE mobno =" + mobno;
var query = connection.query(que, function(err, rows)
{
if(!err){
callback({'response':"Removed Sucessfully"});
}else{
callback({'response':"Error"});
}
});
}
exports.send = function(fromn,fromu,to,msg,callback) {
var que = "SELECT * from users WHERE mobno =" + to;
var query = connection.query(que, function(err, rows)
{
if(rows.length == 0){
callback({'response':"Failure"});
}else {
var to_id = rows[0].reg_id;
var name = rows[0].name;
request(
{ method: 'POST',
uri: 'https://android.googleapis.com/gcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization':'AIzaSyAnHnfHRvXKyIJaSjdR82QQULccWxN4nWg'
},
body: JSON.stringify({
"registration_ids" : [to_id],
"data" : {
"msg":msg,
"fromu":fromu,
"name":fromn
},
"time_to_live": 108
})
}
, function (error, response, body) {
callback({'response':"Success"});
}
)
}});
}
function removeUser(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i].mobno == val) {
arr.splice(i, 1);
return arr;
break;
}
}
}

Categories