console.log a GET request with Node.js - node.js

I'm using the Express framework for my node application. I'm quite new to it so I thought I'd create a defacto "To-Do" application to learn about it. What I'm trying to do it log a request made for debugging purposes. So when I go to:
app.get('/todos/:id', function (req, res) {
var result = db.load(req.params.id);
result ? res.send(result) : res.send(404);
});
I want to a) see what result equals and b) log what happens in my db.load method:
exports.load = function (id) {
todos.findOne({ id: id }, function (err, todo) {
if (!err) {
return todo;
}
});
}
I'm using the mongolian library to access my MongoDB data. I've followed an example by Steve Sanderson: https://github.com/SteveSanderson/nodejs-webmatrix-video-tutorials

app.get('/todos/:id', function (req, res) {
db.load(req.params.id, function(err, result) {
// also handle err
result ? res.send(result) : res.send(404);
});
});
exports.load = function (id, callback) {
todos.findOne({ id: id }, callback);
}

Related

How to retrieve data from db in couchdb

I am trying to fetch data from couch and i follwed the code below
var request = require('request')
var nano = require('nano')('http://localhost:5984/user');
var url = 'http://127.77.3.1:5984/'
var db = 'users2/'
var id = 'document_id'
exports.insertdata = function (req, res) {
var data = req.body;
var item = {
name: data.name,
skills: data.skills,
experience: data.experience
};
nano.insert(item,(err, result) => {
if(!err){
//awesome
}if(result){
console.log(result)
response = {status:'success',data:result};
}
res.send(response);
});
};
exports.getdata = function (req, res) {
nano.getDoc('25f2b6d1e5b83887a42c74bc9b000647',(err, result) => {
if(!err){
//awesome
console.log(err)
}if(result){console.log(result)
console.log('inserted')
response = {status:'success',data:result};
}
res.send(response);
});
};
I am getting the following error
nano.getDoc is not a function
I am trying to fetch data from couch and i follwed the above code,i am not sure about the commands ....can anyone please suggest me some help..........
There is no getDoc in nano as far as I know. There is get. Maybe try changing this:
nano.getDoc('25f2b6d1e5b83887a42c74bc9b000647', (err, result) => {
});
to:
nano.get('25f2b6d1e5b83887a42c74bc9b000647', (err, result) => {
});
and see if that works.
For example here is a simplest query to the CouchDB database that powers the npm registry:
var nano = require('nano');
var db = nano('https://skimdb.npmjs.com/registry');
db.get('rsp', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
Here rsp is the document id, which is a module's name on npm.
In your case it might work if you change getDoc to get. For other function names see the documentation at:
https://www.npmjs.com/package/nano

Node/Express function and callback are not breaking with return

I am creating a 'refresh data' function in Node and I cannot figure out where to place the callbacks and returns. The function continues to run. Below is a list of things the function should do. Could someone help out?
Check if a user has an api id in the local MongoDB
Call REST api with POST to receive token
Store token results in a MongoDB
Terminate function
./routes/index.js
router.post('/refresh', function(req, res) {
var refresh = require('../api/refresh');
refresh(req, function() { return console.log('Done'); });
});
../api/refresh.js
var callToken = require('./calltoken');
var User = require('../models/user'); // Mongoose Schema
module.exports = function(req, callback) {
User.findOne( {'username':req.body.username}, function(err, user) {
if(err) { console.log(err) }
if (user.api_id == 0) {
callToken.postToken(req.body.username, callback);
} else { // Do something else }
});
};
./calltoken.js
var request = require('request');
var Token = require('../models/token'); // Mongoose Schema
module.exports = {
postToken: function(user, callback) {
var send = {method:'POST', url:'address', formData:{name:user} };
request(send, function(err, res, body) {
if(err) { console.log(err) }
if (res.statusCode == 201) {
var newToken = new Token();
newToken.token = JSON.parse(body).access_token['token'];
newToken.save(function(err) {
if(err) { console.log(err) }
return callback();
});
}
});
}
};
I'm not an expert in Express but everywhere in you code in lines with if(err) { console.log(err) } you should stop execution (maybe of course not - up to you app) and return 400 or 500 to client. So it can be something like
if(err) {
console.log(err);
return callback(err); // NOTICE return here
}
On successful execution you should call return callback(null, result). Notice null as a first argument - it is according nodejs convention (error always goes as first argument).

Sails Js - Accessing multiple controller at the same time

I have a problem with accessing multiple controller at the same time,
example I'm accessing the method "access" while "access" is active, I can't use/access the method "other" or other controllers in the client side,
but when the looping in "access" is done, I can use other methods or controllers, is SailsJs controller Single Threading?
access: function (req, res) {
// Assume that I'll generate 1k data and I dont have problem about that
// my problem is while generating 1k data i cant access my other Controller/Method
// any solution about my problem thanks :)
// NOTE** this is just a example of the flow of my program
// In creating data Im using Async
while(x <= 1000) {
Model.create(etc, function (err, ok) {
if(err) console.log(err)
});
x++;
}
res.view('view/sampleview');
},
other: function (req, res) {
res.view('view/view');
},
All controllers and actions are avaible in sails.contollers variavel Mike sails.controllers.mycontroller.access (req, res);
run in parallel, all at same time:
access: function (req, res) {
var createFunctions = [];
while(x <= 1000) {
createFunctions.push(function(done) {
Model.create(etc).exec(function (err, ok) {
if(err) return done(err); // err
done(); //success
});
})
x++;
}
async.parallel( createFunctions, function afterAll(err) {
sails.controllers.mycontroller.other (req, res);
//res.view('view/sampleview');
});
},
other: function (req, res) {
res.view('view/view');
},
run in series, one by one:
access: function (req, res) {
var createFunctions = [];
while(x <= 1000) {
createFunctions.push(function(done) {
Model.create(etc).exec(function (err, ok) {
if(err) return done(err); // err
done(); //success
});
})
x++;
}
// run in series, one by one
async.series( createFunctions, function afterAll(err) {
sails.controllers.mycontroller.other (req, res);
//res.view('view/sampleview');
});
},
other: function (req, res) {
res.view('view/view');
},

Get monk to play well with Q.all

I have a collection of posts and a collection of users. When returning the list of posts, I want to resolve the references to users. This means making an async call for every row of the users. When monk returns a promise, it returns something that responds to "complete" or "success". Q expects something responding to "then". I need to use Q.all to wait for all the users to be fetched into the posts, but I can't make it play well with monk's promise style.
Here is my attempt.
exports.posts = function (req, res) {
req.posts.find()
.complete(function(err, posts) {
handle(err, res, posts);
var postsWithUsers = posts.map(function(post) {
return req.users.findOne({_id: post.userId}).complete(function(err, result) {
post.user = result;
});
});
Q.all(postsWithUsers.map(function(monkPromise) {
monkPromise.then = monkPromise.complete
}), function(err, results) {
console.log("done with all posts");
});
});
};
Just for everyone else out there. This is one solution, perhaps not the best.
exports.posts = function (req, res) {
req.posts.find()
.complete(function(err, posts) {
handle(err, res, posts);
var postsWithUsers = posts.map(function(post) {
var deferred = Q.defer();
return req.users.findOne({_id: post.userId}).complete(function(err, result) {
post.user = result;
deferred.resolve(result);
});
return deferred.promise;
});
Q.all(postsWithUsers, function(err, results) {
console.log("done with all posts");
});
});

function returning values as undefined in nodejs

I am working on a NodeJs project for the first time. And now i am stuck with the function returning values through JS and getting values to use in express.
var dbitems = "before fn";
function refreshData(callback) {
db.open(function (err, db) {
if (!err) {
db.collection('emp').find().toArray(function (err, items) {
dbitems = items;
callback(JSON.stringify(items));
});
}
else {
console.log("Could not be connnected" + err);
dbitems = {"value":"not found"};
}
});
}
}
refreshData(function (id) { console.log(id); });
This function retrieves values perfectly from refreshData and writes into console. But what I need is to use the retrieved value to send into express html file from this function by "returnedData"
exports.index = function (req, res) {
var valrs = refreshData(function (id) {
console.log(JSON.parse(id)); ---this again writes data perfectly in the console
});
console.log(valrs); -------------------but again resulting in undefined
res.render('index', { title: 'Express test', returnedData: valrs });
};
Any help would be appreciated.
Thanks & Regards,
Luckyy.
You need to render this after the database request finishes.. so it needs to be called from within the callback.
exports.index = function (req, res) {
refreshData(function (id) {
res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
});
};
it's asynchronous so you can't just put values in order, needs to go through the callbacks.

Resources