updating mongodb using new json object - javascript

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.

Related

How to connect to mysql properly in nodejs?

what i trying to do here is query to mysql database, but when i execute my query, it just loading forever, no error untill it timed out, how to solve this? below is my db.js code :
Db.js :
var mysql = require("mysql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new mysql.createConnection(settings.dbConfig);
conn.connect(function(err){
if(err){
console.log(err + "1");
return;
}
console.log(conn.log + "2");
})
};
and here is my bassCtrl.js :
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
exports.get_user = function(req, resp) {
db.executeSql("select * from mst_user", function(data, err) {
console.log("in controller");
if (err) {
httpMsgs.show500(req, resp, err);
} else {
httpMsgs.sendJson(req, resp, data);
};
});
};
and here is my routes.js
var express = require('express');
var bassCtrl = require("../controllers/bassCtrl");
var httpMsgs = require("../core/httpMsgs");
var jwt = require('jsonwebtoken');
module.exports = function(app, express) {
var router = express();
router.route('/get_user').get(bassCtrl.get_user);
return router;
};
below is my HttpMsgs.js :
var settings = require("../settings");
exports.show500 = function(req, resp, err) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head><body>500: Internal Error. Details: " + err + "</body></html>");
} else {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Error occurred: " + err }));
}
resp.end();
}
exports.sendJson = function(req, resp, data) {
resp.writeHead(200, {"Content-Type":"application/json"});
if (data) {
resp.write(JSON.stringify(data));
}
resp.end();
}
exports.show405 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(405, "Method not supported", {"Content-Type":"text/html"});
resp.write("<html><head><title>405</title></head><body>405: Method not supported.</body></html>");
} else {
resp.writeHead(405, "Method not supported", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Method not supported"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(404, "Resource not found", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>404: Resource not found.</body></html>");
} else {
resp.writeHead(404, "Resource not found", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Resource not found"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>413: Request Entity Too Large.</body></html>");
} else {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Request Entity Too Large"}));
}
resp.end();
}
exports.send200 = function(req, resp) {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "success", code: 200}
));
resp.end();
}
exports.showHome = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(200, {"Content-Type":"text/html"});
resp.write("<html><head><title>200</title></head><body>Your server connected dude ! :)</body></html>");
} else {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "Your server connected dude ! :)"}
));
}
resp.end();
}
and here is my settings.js :
exports.dbConfig = {
user: "root",
password: "",
host: "localhost",
database: "zouk"
};
exports.httpMsgsFormat = "json";
when i trigger localhost:5000/get_user, it just loading till it timed out, and my console.log print this line console.log(connection.log + "2"); with undefined as the value. is there something i missing?
wait a minute, why my question rated minus?
You didn't execute your query in Db.js file, and your code don't call the callback too, that's why it run until timeout.
var connection = mysql.createConnection({
host : ***,
user : ***,
password : ***,
database : ***,
});
connection.connect();
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
//your callback go here.
// callback(rows);//pass whatever you need in.
});
connection.end();
Plus, your controller have no require for httpMsgs. I think it should have.

Button for remove a object in mongoDB

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 :(

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

in node.js with express req.session is undefined inside my require() module

I'm wondering why req.session.username is undefined in the tag >>>DOESNT WORK<<< while it does work in the tag >>>THIS DOES WORK<<< . I brought in req as an argument to my module but it seems I'm supposed to do something else? The /ajax route is accessed via a ajax call and it does set the session variable in >>>THIS DOES WORK<<<
//index.js file
var express = require('express');
var router = express.Router();
var app = express();
var functions = require('../public/javascripts/functions.js');
router.post('/ajax', function(req, res , next){
var username = req.param("username");
var password = req.param("password");
var operation = req.param("operation");
else if (operation === "validate")
{
async.series([
function()
{
functions.validate(username, password, req);
}
], function(err,result)
{
if (err)
return console.log(err);
console.log(result);
});
//req.session.username = "yaryar"; >>>THIS DOES WORK<<<
}
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
module.exports = router;
functions.js file:
module.exports = {
validate: function(username, password, req) {
var url = 'mongodb://localhost';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
MongoClient.connect(url, function(err, db)
{
assert.equal(null, err);
console.log("Connected correctly to server.");
var cursor = db.collection('users').find({username : username});
cursor.each(function(err,doc,req)
{
assert.equal(err, null);
if (doc != null)
{
console.log("user found: " + doc.username);
req.session.username = "ttyy"; // >>>DOESNT WORK<<<
return true
}
else
{
console.log("user not found");
return false;
}
});
//db.close();
});
}
};
you're overwriting req by doing cursor.each(function(err,doc,req) change it to cursor.each(function(err,doc,arr) and it will work

Cannot call method 'send' of undefined(response is undefined) in express js

I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data
I am able to get the data from the database but couldnt send that back to the server(app.js)
app.js
var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
var result=maildata.getMailData(input);
response.send(result);
response.end();
});
app.listen(8888);
console.log('Server is running on port 8888');
maildata.js
exports.getMailData=function(data,response) {
var stop_name= data;
connection.query("select stop_name,stop_comment from stoplist where stop_name= '"+stop_name+"' limit 1",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString1= JSON.stringify(rows);
connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString2 = JSON.stringify(rows);
connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString3 = JSON.stringify(rows);
var result=jsonString1+'/'+jsonString2+'/'+jsonString3;
response.send(result);
}
});
}
});
}
});
}
Thanks in Advance
How about sending response along when you call the function?
var result=maildata.getMailData(input); // something missing here
Your getMailData function expects two arguments:
exports.getMailData=function(data,response) { ... }
but you give it only one:
var result=maildata.getMailData(input);
Which makes the value of the response argument undefined.
Here is what you should do:
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
maildata.getMailData(input, response);
});
and let maildata.getMailData handle the response sending, as you did in response.send(result);
I have used asynchronous callback method in my app.js.
I got the result
var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});
Thanks all

Categories