node js callback function - javascript

I am new to nodeJs. In my code I have a asynchronous function for finding records from mongoDB.
var restify = require('restify');
var mongojs = require('mongojs');
var ip_addr = '127.0.0.1';
var port = '8080';
var server = restify.createServer({
name : "signapp"
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
var connection_string = '127.0.0.1:27017/signapp';
var db = mongojs(connection_string, ['signapp']);
var docDetails = db.collection("SIGN_DOCUMENT_DETAILS");
var PATH = '/documents'
server.post({path : PATH + '/:search', version: '0.0.1'}, searchDoc);
function searchDoc(req, res, next)
{
var criteria = {};
criteria.DOC_NAME = req.params.DOC_NAME;
if (criteria.DOC_NAME !== '' || criteria.DOC_NAME !== null)
{
docDetails.find({DOC_NAME : criteria.DOC_NAME}, function(err, users){
if( err || !users){
console.log("No record found");
}
else {
console.log('record found');
}
});
}
}
In my request I pass a string parameter. I am getting 'record found' response in my console when the condition is matched.
But the problem is I am getting response in console as 'record found' even when the find condition fails. I tried a lot ti find a solution but failed.
Please tell me where I went wrong in my code. A solution for this bug will be greatly appreciated. Thanks in advance.

change your condition like
if( err){
console.log("An error occurred");
} else if(!users || users.length==0) {
console.log("No results found");
} else {
console.log('record found');
}
You need to add a condition to check if the returned array was empty.
note :
javascript empty array seems to be true and false at the same time gives a proper explanation on why u should not use if(!users) to check if the array was empty.

Related

How can I overwrite and append data to the same file multiple times in node js

I have a "clients.txt" file where I have a list of emails. I try to run a program for sending emails where I chose a number of emails to use from the file, in that case the number is 2. After I use the two emails I want to overwrite "clients.txt" without them. The problem is when I try to run the code just for one single time every thing is working! but if I make a loop something is wrong. Looking forward to see any help from you guys. Thanks! I add the code bellow. PS: Sorry for my bad english!
function readEmails(){
const fs = require('fs');
clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');
let filtered = clients_list.filter(function (el) {
return el != null && el != '';
});
return filtered
}
function dump_array(arr, file){
let fs = require('fs');
let file = fs.createWriteStream(file);
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v + '\n'); });
file.end();
}
while_var = 0;
while (while_var < 2){
while_var ++;
let all_clients = readEmails();
let selected_clients = [];
if (all_clients.length > 0){
selected_clients = all_clients.splice(0,2);
dump_array(all_clients, 'clients.txt');
console.log(selected_clients);
}else{
console.log('No more clients')
}
}
const fs = require('fs');
function readEmails(){
const clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');
const filtered = clients_list
// clear false, 0 and undefined too
.filter(el => !!el)
// remove extra spaces and \r symbols
.map(el => el.trim());
return filtered;
}
function dump_array(arr, file){
// Here you need sync method.
fs.writeFileSync(file, arr.join('\n'));
// And here was 'already declared' error in orginal code
}
let while_var = 0;
while (while_var++ < 2){
let all_clients = readEmails();
let selected_clients = [];
if (all_clients.length > 0){
selected_clients = all_clients.splice(0,2);
dump_array(all_clients, 'clients.txt');
console.log(selected_clients);
}else{
console.log('No more clients')
}
}

Get first and last name on Windows with Electron

I'm have problems with get the first name and last name with electron and node js, i have the username, but i need first name and last name.
Image example
I tried:
const username = require('username');
const os = require ('os');
const computerName = os.hostname();
const fullname = require('fullname');
console.log(os.userInfo());
// Console:
//{ uid: -1,
// gid: -1,
// username: 'mauroh',
// homedir: 'C:\\Users\\mauroh',
// shell: null
//}
console.log("computerName: ", computerName);
console.log("username: " , username());
// Console:
// computerName: DEV
// username: mauroh
fullname().then(name => {
console.log(name);
});
// Console:
// mauroh
Is there any way to get the first and last name? or profile name with electron or node js ?
Example: Mauro HUC
Note: This app is only for windows.
Thanks!
The "fullname" module does in some cases not return the name as it can't be found. This is clearly stated in the GitHub repository for the module.
I found a way to do it,
I am using the username package to obtain the logged-in user.
async getUsername() {
return await username();
}
Then in node js and electron you can use the child processes, child_process docs.
When you perform the command net user <username> or net user <username> / domain you get all the user information, among all the information is the full name, also the name can be empty.
const child = require('child_process');
let exec = child.exec;
// And make a function for do command
function execute(command, callback){
exec(command, function(error, stdout, stderr){
let result = null;
if(!error){
var splitted = stdout.split("\n");
var username = '';
var fullname = '';
for(var i=0; i < splitted.length; i++){
if(splitted[i].search("User name") != -1){
splitted[i] = splitted[i].replace('User name',' ');
splitted[i] = splitted[i].trim();
username = splitted[i];
}else if(splitted[i].search("Full Name") != -1){
splitted[i] = splitted[i].replace('Full Name',' ');
splitted[i] = splitted[i].trim();
fullname = splitted[i];
}
}
let data = {
username: (username) ? username.toLowerCase() : null,
fullname: (fullname) ? fullname: null
}
result = data;
} else{
result = null;
}
callback(result);
});
};
This way you can get the user's full name.

After moving the node, from prevRef to newRef how do I update a specific data inside Firebase?

I use the code below to copy a certain data from ('Pending') node to ('Approved') node. It only copies the node including the username and the request_status of the data. How can I update the request_status inside the userid after being copied?
var oldRef = firebase.database().ref().child('Request').child('Pending');
var newRef = firebase.database().ref().child('Request').child('Approved');
function moveFbRecord(oldRef, newRef) {
oldRef.once('value', function(snap) {
newRef.update( snap.val(), function(error) {
if( !error ) { oldRef.remove();}
else if( typeof(console) !== 'undefined' && console.error ) { console.error(error); }
});
});
newRef.limitTolast(1).update({ snap.val().request_status: "Approved" });<<< I tried inserting this code but I think it messes up every code in my .js file
}
Where should I put the update line of code?
newRef.limitTolast(1).update({ snap.val().request_status: "Approved" });
To update the status in the new node:
oldRef.once('value', function(snap) {
var data = snap.val();
data.request_status = "Approved";
newRef.update(data, function(error) {
if( !error ) { oldRef.remove(); }
else if( typeof(console) !== 'undefined' && console.error ) { console.error(error); }
});
});
You could even combine the deleting of the old node and the writing of the new one in a single multi-location update. They key to this is that you give the complete path of all data you want Firebase to update:
oldRef.once('value', function(snap) {
var data = snap.val();
data.request_status = "Approved";
var updates = {};
updates["Request/Approved/"+snap.key] = data
updates["Request/Pending/"+snap.key] = null;
firebase.database().ref().update(updates);
});
The important advantage of this approach is that either all these updates succeed or none of them do. So there's no chance of any lingering data in the old location.

My program only gets the first value of the array and i need all

im having a problem in my program. i need to pass all the values of my array to the database. Here is my program..
exports.post = function(req, res){
var obj = {};
var eacode = req.body.eacode;
db.all("SELECT * FROM localarea_listings WHERE eacode= ? ",eacode, function(err,rows2){
rows2.forEach(function (row2) {
var hcn = row2.hcn;
var shsn = row2.shsn;
console.log(hcn);
console.log(shsn);
});
db.all("UPDATE localarea_listings SET INTERVIEW_STATUS = ? WHERE eacode = ?
and hcn =? and shsn = ?",[req.body.INTERVIEW_STATUS, req.body.eacode,
req.body.hcn, req.body.shsn],function(err,rows){
if (err)
{
console.log("Error Updating : %s ",err );
}
else
console.log("Success updating localarea_listings");
});
});
};
The data will process depending on the variable eacode from the database localarea_listings.db
Lets say the values hcn is 1,2,3,4,5 and shsn is 6,7,8,9,10 respectively.
when i print hcn and shsn, the value will display what i want, which is
hcn=[1,2,3,4,5] and shsn=[6,7,8,9,10]
The problem will starts here, when i update it, it only update the first value of the array which is 1 for hcn and 6 for shsn. i tried using row2[0].hcn and row2[0].shsn but it will cause error..
I hope my question is clear. Thanks!
You need to move the update inside the forEach
exports.post = function(req, res) {
var obj = {};
var eacode = req.body.eacode;
db.all("SELECT * FROM localarea_listings WHERE eacode= ? ", eacode, function(err, rows2) {
rows2.forEach(function(row2) {
var hcn = row2.hcn;
var shsn = row2.shsn;
console.log(hcn);
console.log(shsn);
db.all("UPDATE localarea_listings SET INTERVIEW_STATUS = ? WHERE eacode = ? and hcn = ? and shsn = ? ",[req.body.INTERVIEW_STATUS, req.body.eacode, hcn, shsn], function(err, rows) {
if (err) {
console.log("Error Updating : %s ", err);
} else
console.log("Success updating localarea_listings");
});
});
});
};

node.js only passing filled out values to mongodb

I'm working on a project in node.js, mongodb, and express that has to deal with transactions.
I can hard code the variables to be put into mongodb, but if not all the fields are being filled out (not all are required) then I'm just putting empty data into the database.
this code works:
var d = new Date();
var n = d.toJSON();
var date = n;
var address = req.body.property_address;
var client_name = req.body.client_name;
var sales_price = req.body.sales_price;
var commission_percent = req.body.commission_percent;
var referral = req.body.referral;
var donation = req.body.donation;
var client_source = req.body.client_source;
var client_type = req.body.client_type;
var notes = req.body.notes;
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc) {
console.log("there is no error, and this does not already exist");
var newTransaction = new Transaction();
newTransaction.date = date;
newTransaction.address = address;
newTransaction.client_name = client_name;
newTransaction.sales_price = sales_price;
newTransaction.commission_percent = commission_percent;
newTransaction.referral = referral;
newTransaction.donation = donation;
newTransaction.client_source = client_source;
newTransaction.client_type = client_type;
newTransaction.notes = notes;
newTransaction.save(function(err) {
if(!err){
console.log("successfully saved");
res.json(200, {message: newTransaction.date});
} else {
res.json(500, {message: "Could not create transaction. Error: " + err})
}
});
}
});
But what's the point of putting in a value that doesn't exist into mongodb? Isn't that one of the things that is supposed to be awesome about it? And my thinking is, it takes away possible queries that I might be able to do in the future.
Would it be possible to do something more like this?
Transaction.findOne({ name: { $regex: new RegExp(date, 'i' ) } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
newTransaction.key = req.body[key];
}
}
}
});
update
This is the code I ended up using that worked.
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
if(req.body[key] != ''){
newTransaction[key] = req.body[key];
}
}
}
}
});
This is perfectly fine behaviour. You can still query a field that doesn't exist in all documents, as a non-existent field is the same as not equal.
This means the loose definition of the documents is still retained.
Looks fine to me, but I would probably not want to trust just ANY client data to serve as key, depending on how you deploy.
Perhaps:
['date', 'address', 'client_name'/*,...*/].forEach(function(key)
{
/* ... */
if (key in req.body) newTransaction[key] = req.body[key];
});

Categories

Resources