Conditionally Rendering EJS Template Views to the Same Path - javascript

So, very newbie question, but I searched for a couple hours and couldn't find this specific problem (I know I'm doing something dumb).
I am grabbing data from a simple sqlite database table, processing if certain rows are a specific value, pushing them into a table (which I use to push to one of the EJS pages), and then want to render a page based on if there is any data in the table or not.
I want to read the table at a certain interval (using setInterval) and then if there has been a change, update the "view".
All of it has gone decently well, except for when the EJS page actually has to switch from one page to another. I'm not even sure if it's possible to do this, once it's rendered. But, I'd prefer to just render a different page on the same path ('/') that changes on browser refresh.
The initial conditional statement renders the correct EJS page, but like I said, once it needs to switch, the page remains on browser refresh.
I've tried moving the placement of the conditional in multiple places (inside the "get", outside, etc.).
Also tried doing the "if" statement inside a single EJS page, but it just won't refresh once the initial page is rendered and then the function is called again with the setInterval.
var sqlite3 = require('sqlite3').verbose();
var express = require('express');
var app = express();
fs = require('fs')
app.set('view engine', 'ejs');
function query(){
var db = new sqlite3.Database('./my_database.sqlite', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
var sql = `SELECT column1 column1
FROM myTable
WHERE column1 = ?`;
var mkts = []
db.each(sql, ['a'], (err, row) => {
if (err) {
throw err;
}
mkts.push(row.column1);
console.log(mkts);
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
console.log(mkts.length);
if(mkts.length>0){
console.log(true);
app.get('/', function(req, res){
res.render('alert', {mkts:mkts});
});
}else{
console.log(false);
app.get('/', function(req, res){
res.render('index', {mkts:mkts});
});
}
});
};
query();
setInterval(() => query(), 10000);
app.listen(3000);
So basically after opening and then querying the data I want, I'm running the get and render at the db.close. In this code, I can get the "true" and "false" to log appropriately when the DB changes, but the render will not change once the overarching function is run once.
Sorry if its hard to read, but it's been driving me nuts all day.

Your logic (retrieving the datas, view switch) has to be INSIDE your app.get("/"...
Here, you're querying the datas only once (on server) startup and set a static route with static datas.
Try something like this :
// connect to db on startup
var db = new sqlite3.Database('./my_database.sqlite', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
// define your routes
app.get('/', function(req, res){
// when route is asked by your browser retrieve the datas
var sql = `SELECT column1 column1
FROM myTable
WHERE column1 = ?`;
var mkts = []
db.each(sql, ['a'], (err, row) => {
if (err) {
throw err;
}
mkts.push(row.column1);
console.log(mkts);
});
// render the good view according to your datas
if(mkts.length>0){
res.render('alert', {mkts:mkts});
}
else {
res.render('index', {mkts:mkts});
}
});
app.listen(3000);
In addition, your setInterval to refresh the view cannot be done here, the "refresh" has to be asked by the client. In your view simply put something like this in javacript :
<script>setTimeout(function(){document.location.reload();}, 1000);</script>

Related

Returning queries from couchdb using nano

i've written a simple module to handle my couchdb CRUD operations using nano, however i'm having hardship returning from the results i query from the couch database. My Code is as follows.
couchdb.js
//Select from couch view
exports.couchSelect=function (_db, document,view) {
return _db.view(document, view,function(err, body){
if(!err){
var rows = body.rows; //the rows returned
console.log(rows);
return rows;
}else{
console.log(err);
}
}
);
}
routes.js
var couchdb = require('./couchdb');
app.get("/orders", function (req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
var insert = couchdb.couchSelect(db, 'orders', 'orders');
console.log(insert);
});
On executing the returned output is only get Node http request parameters without the returned rows, need help to return the actual JSON rows queried.Thanx
You're using nano which use callback to make async calls. Returning _db.view only return a void function. I added comments to tell you what is happening :
exports.couchSelect = function(_db, document, view) {
_db.view(document, view, function(err, body) {
//This will be called after the couchSelect request.
if (!err)
console.log("Callback : " + body.rows);
});
}
//When you use it
var couchdb = require('./couchdb');
app.get("/orders", function(req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
var insert = couchdb.couchSelect(db, 'orders', 'orders');
//This is synchronous. This will be called before the callback is called.
console.log(insert);
});
I decided to use blue-nano which uses promises instead of callbacks and the code is as below.
couchdb.js
var nano = require('nano-blue')('http://localhost:5984');
//Select from couch view
exports.couchSelect=function (_db, document,view) {
return _db.view(document, view);
}
routes.js
app.get("/orders", function (req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
couchdb.couchSelect(db, 'orders', 'all').spread(function (body,header) {
res.send(body.rows);
}).catch(function(err) {
console.log(err.message);
});
});
This works perfectly

get count collection with socket.io-mongodb

I'm trying to make a simple task.
In the first place, on client side, i'm sending data to server and then i insert these data into my mongodb database.
Then i try to get count of clients from my database.
var express = require('express');
var MONGO_URL = "mongodb://localhost:27017/mydatabase";
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongo = require('mongodb').MongoClient,
fs = require('fs');
var countUserSuscribed =0;
//here i insert data
/* Connection events */
io.on('connection', function (client) {
console.log("User connected");
client.on('InsertNewUser', function (newUser) {
console.log("we ar in InsertNewUser event");
//////////////////////////////////////////////////////////
mongo.connect(MONGO_URL, function (err, db) {
console.log("we are connected to mongodb");
var Users = db.collection('User');
console.log("on crée la collection et on fait l'ajout");
Users.insert({ player: myP }, function (err, o) {
if (err) { console.warn(err.message); }
else { console.log("user inserted into db: user"); }
});
});
})
});
//GET COUNT USER
console.log("here we get count user");
mongo.connect(MONGO_URL, function (err, db) {
countUserSuscribed = Users.count();
console.log("we got " + countUserSuscribed + " user in mongoDB");
});
With this code i can create collections and insert documents but the count function doesn't work and i didn't find much explanations on npm documentation.
Is it possible to use others mongodb functions than insert and collection with socket.io-mongodb ?
If it is, can someone give an example or explain me how to use it?
The count function works but is async function and takes a callback.
here's the fix:
countUserSuscribed = Users.count(function (err,c) { console.log(c) });
https://www.npmjs.com/package/mongodb-autoincrement consider using that. It keeps a track of all inserted document. Plus it has a handy feature to get the next count. Example let's say you inserted two records. If you call next count it will show 3. There fore to get the total documents inserted call get next count - 1. Make sense?
Sorry here is the correct one. https://www.npmjs.com/package/mongoose-auto-increment

Node/Express Redirect After POST

I have an Express post route which updates a mongo db based on data sent to it from a DataTables Editor inline field. So far so good and the database is updating fine. Where it falls over is after the update query executes successfully and I want to then redirect back to the originating page. The Node console seems to indicate that the GET route to the originating page is being called, but the page itself doesn't load.
The code for the POST function is as follows:
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
The GET route works fine when called directly, but seems to halt when called like this.
I'm pretty sure that there's nothing in the POST route that is causing this as the same thing happens when I strip out everything except the redirect itself.
router.post('/test',function(req,res){
res.redirect('/admin');
});
Please help!

Different Get methods in Node-Express Rest API

I have been creating a website with Mean stack and I stuck at some point. I have a mongo db database and I am currently getting each file from database (to show them on Main page) with my Rest Api which is build with Express.
Server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('mongodb://username...', ['myApp']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/myApp', function (req, res) {
db.myApp.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.get('/myApp/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.myApp.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
})
});
app.listen(3001);
console.log('Server running on port 3001');
There is 2 get method and I can understand that because they have different parameters. So when I call them from controllers, there is no problem because if I provide id, it will call the second get method. But for example I want to use something like this in my website;
app.get('/myApp', function (req, res) {
db.myApp.find({}).limit(2).skip(0, function(err, docs) {
console.log(docs);
res.json(docs);
});
});
This get method have no parameter like the first get method in server.js but they do different jobs. This is limiting my search with 2 file. How can I use different get methods like this in my Mean Stack application?
This is my code for calling get method from my main controller. How can I make sure to call specific get method? Thanks..
$http.get('/myApp').success(function(response) { .. });
What you want is not possible. Somehow you need to distinguish between your 2 intentions, either by giving the endpoints different names (like you already suggest in your comment) or by providing for example a query parameter so you could do a call like:
$http.get('/myApp?limit=2').success(function(response) { .. });
When limit is omitted, you could return all results.
Something like:
app.get('/myApp', function (req, res) {
var limit = req.query.limit;
if (limit === undefined) {
// Return everything
} else {
// make sure limit is some valid number
// ... and do a mongo query limited to this number
}
});

Nano Couchdb cant get up a folder

I have a database called "visitors" he has the same _ids as another database called "users". I use views so one a user goes to http://localhost:3000/sitename, it uses the data inside _utiles/users/sitename, and it works smooth.
now inside that site I have a form, what I want to do--> the data from the form need to be send to /visitors/sitename/NEW ID/Data, all I manage to do is just open up inside sitename some data, and only for the first time, after that, all gets update conflicts.
I read everything Nano - Couchdb has to offer, cant seem to figure that out.
here is code example:
app.post('/update', function(req, res){
var sitename=req.body.title;
var arrive =req.param('arrive');
var fsname = req.param('fsname');
var number = req.param('number');
var no_arrive_reason = req.param('no_arrive_reason');
update_db = nano.db.use(sitename)
update_db.insert({arrive: arrive, fsname: fsname ,number:number,no_arrive_reason:no_arrive_reason},fsname, function(err, body , header) {
if (!err)
console.log(body);
else{
// console.log(err);
nano.db.create(fsname, function(err, body) { // want to create it inside /visitors/sitename/ -- and it's created just in main db
if (!err) {
console.log('database:'+fsname+'was created');
}
});
}
});
});
thanks a head!

Categories