Nano Couchdb cant get up a folder - javascript

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!

Related

Conditionally Rendering EJS Template Views to the Same Path

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>

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

How can I display the output(HTML) depending on its id on node js using sqlite

Here is my code on Node JS. And can you give an example what will i add in the HTML code. Thank you
exports.get = function(req, res){
db.all("SELECT * FROM f11", function(err,rows){
rows.forEach(function (row) {
console.log('row: ' + row.GIVENNAME);
});
// console.log(rows);
res.render('form11.ejs',{array:rows});
});
};
I see you are using sqlite3 npm package for sqlite.
After looking at your code, You can try this to achieve what you want:
change get route to have a param id like this in your server.js
app.get('/legone/survey/surveyform/form11/:id', form11.get);
And, write your get function like this:
exports.get = function(req,res){
var id = req.params.id;
db.all("SELECT * FROM f11 WHERE id = ?",id, function(err,rows){
rows.forEach(function (row) {
console.log('row: ' + row.GIVENNAME);
});
res.render('form11.ejs',{array:rows});
});
};
And your route will be something like this:
http://localhost/legone/survey/surveyform/form11/23
where 23 is the id. Put whatever you want in its place.
if you are using ajax calls, it will look like this:
$http.get('/legone/survey/surveyform/form11/23')
.success(function(response){
//handle response
})
.error(function(error){
//handle error
});
you can test the route via POSTMAN or something like that.
For more information, you can Read Sqlite3 Wiki API Documentation or, directly about params and Callbacks here.
Also, after looking at your code you need lot of restructuring. You should define all your routes in one file and then use it inside app.js.
Something like this :
//define all the routes that start from '/legone/survey/surveyform' in one file
//(let it be 'surveryRoutes.js')
//and then include it in your app.js.
var surveyRoutes = require(./routes/surveyRoutes);
app.use('/legone/survey/surveyform',surveyRoutes);
If you want to get an id and query on that then:
First you'll need to pass an id in the request query. Like http://localhost/api/getUser?id=23
exports.getUser = function(req, res){
var user_id = req.query.id;
db.all("SELECT * FROM f11 WHERE id="+user_id, function(err,row){
console.log(row); // Since you'll only get one row
res.render('form11_detail.ejs',{data:row});
});
};
If you add this code then for displaying only one you could use 'getUser' function and for displaying all data, you could use your 'get' function.

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!

Categories