Can I use try catch like this in node.js? - javascript

I'm making node server, to show up all elements in specific folder.
and have to stop function when path === seekPath,
can I throw result data and catch it to show all elements?
app.get('/view/:id', function(req, res){
if (req.session.key) {
const rawData = fs.readFileSync(__folderTree + req.params.id + ".json")
const jsonData = JSON.parse(rawData)
const seekPath = __storage + req.params.id + "/" + req.query.path
console.log(seekPath)
try {
seekFolder(jsonData, seekPath)
} catch (result) {
showElements(result)
}
}
else {
res.redirect('/login');
}
})
function seekFolder(jsonData, seekPath) {
jsonData.children.forEach(element => {
if(element.type === 'directory'){
console.log("compare " + element.path + " & " + seekPath)
if(element.path === seekPath){
throw(element.children)
}
else{
seekFolderElements(element, seekPath)
}
}
});
}
function showElements(jsonArrData) {
jsonArrData.forEach(element => {
if(element.type === 'directory'){
console.log("!!"+element.name)
showElements(element)
}
else{
console.log("!!"+element.name)
}
});
}

Related

express-ntlm: how to get additional attribute value in req.ntlm?

In express-ntlm package i have added password attribute but i'm not able to get its value while i provide in private window of chrome. I always getting empty value.
My code is:
/* jshint node:true */
// node.js modules
var url = require('url');
// 3rd-party modules
var _ = require('underscore'),
async = require('async');
// Custom modules
var Cache = require('./Cache'),
NTLM_AD_Proxy = require('./NTLM_AD_Proxy'),
NTLM_No_Proxy = require('./NTLM_No_Proxy'),
utils = require('./utils');
const { Domain } = require('domain');
// Globals
var cache = new Cache();
module.exports = function(options) {
// Overwrite the default options by the user-defined
options = _.extend({
badrequest: function(request, response, next) {
response.sendStatus(400);
},
internalservererror: function(request, response, next) {
response.sendStatus(500);
},
forbidden: function(request, response, next) {
response.sendStatus(403);
},
unauthorized: function(request, response, next) {
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM');
response.end();
},
prefix: '[express-ntlm]',
debug: function() {
},
domaincontroller: null,
getConnectionId(request, response) {
return utils.uuidv4();
}
}, options);
function ntlm_message_type(msg) {
if (msg.toString('utf8', 0, 8) != 'NTLMSSP\0') {
return new Error('Not a valid NTLM message:', msg.toString('hex'));
}
var msg_type = msg.readUInt8(8);
if (!~[1, 2, 3].indexOf(msg_type)) {
return new Error('Incorrect NTLM message Type', msg_type);
}
return msg_type;
}
function parse_ntlm_authenticate(msg) {
var DomainNameLen = msg.readUInt16LE(0x1C),
DomainNameBufferOffset = msg.readUInt32LE(0x20),
DomainName = msg.slice(DomainNameBufferOffset, DomainNameBufferOffset + DomainNameLen),
UserNameLen = msg.readUInt16LE(0x24),
UserNameBufferOffset = msg.readUInt32LE(0x28),
UserName = msg.slice(UserNameBufferOffset, UserNameBufferOffset + UserNameLen),
PasswordLen = msg.readUInt16LE(0x34),
PasswordBufferOffset = msg.readUInt32LE(0x38),
Password = msg.slice(PasswordBufferOffset, PasswordBufferOffset + PasswordLen),
WorkstationLen = msg.readUInt16LE(0x2C),
WorkstationBufferOffset = msg.readUInt32LE(0x30),
Workstation = msg.slice(WorkstationBufferOffset, WorkstationBufferOffset + WorkstationLen);
if (utils.isFlagSet(msg.readUInt8(0x3C), utils.toBinary('00000001'))) {
DomainName = DomainName.toString('utf16le');
UserName = UserName.toString('utf16le');
Password = Password.toString('utf16le');
Workstation = Workstation.toString('utf16le');
} else {
DomainName = DomainName.toString();
UserName = UserName.toString();
Password = Password.toString();
Workstation = Workstation.toString();
}
return [UserName, Password, DomainName, Workstation];
}
function decode_http_authorization_header(auth) {
var ah = auth.split(' ');
if (ah.length === 2) {
if (ah[0] === 'NTLM') {
return ['NTLM', new Buffer(ah[1], 'base64')];
}
}
return false;
}
function connect_to_proxy(type1, callback) {
var domain = options.domain;
var proxy,
ntlm_challenge;
async.eachSeries(!options.domaincontroller ? [ -1 ] : typeof options.domaincontroller === 'string' ? [ options.domaincontroller ] : options.domaincontroller, function(server, eachDomaincontrollerCallback) {
if (!server || ntlm_challenge) return eachDomaincontrollerCallback();
if (server === -1) {
options.debug(options.prefix, 'No domaincontroller was specified, all Authentication messages are valid.');
proxy = new NTLM_No_Proxy();
} else if (!server.indexOf('ldap')) {
var serverurl = url.parse(server),
use_tls = serverurl.protocol === 'ldaps:',
decoded_path = decodeURI(serverurl.path);
options.debug(options.prefix, 'Initiating connection to Active Directory server ' + serverurl.host + ' (domain ' + domain + ') using base DN "' + decoded_path + '".');
proxy = new NTLM_AD_Proxy(serverurl.hostname, serverurl.port, domain, decoded_path, use_tls, options.tlsOptions);
} else {
return eachDomaincontrollerCallback(new Error('Domaincontroller must be an AD and start with ldap://'));
}
proxy.negotiate(type1, function(error, challenge) {
if (error) {
proxy.close();
proxy = null;
options.debug(options.prefix, error);
return eachDomaincontrollerCallback();
}
ntlm_challenge = challenge;
return eachDomaincontrollerCallback();
});
}, function(error) {
if (error) return callback(error);
if (!proxy) {
return callback(new Error('None of the Domain Controllers are available.'));
}
return callback(null, proxy, ntlm_challenge);
});
}
function handle_type1(request, response, next, ntlm_message, callback) {
cache.remove(request.connection.id);
cache.clean();
connect_to_proxy(ntlm_message, function(error, proxy, challenge) {
if (error) return callback(error);
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM ' + challenge.toString('base64'));
response.end();
cache.add(request.connection.id, proxy);
return callback();
});
}
function handle_type3(request, response, next, ntlm_message, callback) {
var proxy = cache.get_proxy(request.connection.id);
var userDomainWorkstation = parse_ntlm_authenticate(ntlm_message),
user = userDomainWorkstation[0],
pass = userDomainWorkstation[1],
domain = userDomainWorkstation[2],
workstation = userDomainWorkstation[3];
if (!domain) {
domain = options.domain;
}
proxy.authenticate(ntlm_message, function(error, result) {
if (error) return callback(error);
var userData = {
DomainName: domain,
UserName: user,
Password: pass,
Workstation: workstation,
Authenticated: false
};
request.ntlm = userData;
response.locals.ntlm = userData;
request.connection.ntlm = userData;
if (!result) {
cache.remove(request.connection.id);
options.debug(options.prefix, 'User ' + domain + '/' + user + ' authentication for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.forbidden(request, response, next);
} else {
userData.Authenticated = true;
return next();
}
});
}
return function(request, response, next) {
if (!request.connection.id) {
request.connection.id = options.getConnectionId(request, response);
}
var auth_headers = request.headers.authorization;
var user = request.connection.ntlm;
if (user && user.Authenticated) {
options.debug(options.prefix, 'Connection already authenticated ' + user.DomainName + '/' + user.UserName);
if (auth_headers) {
if (request.method != 'POST') {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
} else {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
}
if (!auth_headers) {
options.debug(options.prefix, 'No Authorization header present');
return options.unauthorized(request, response, next);
}
var ah_data = decode_http_authorization_header(auth_headers);
if (!ah_data) {
options.debug(options.prefix, 'Error when parsing Authorization header for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.badrequest(request, response, next);
}
var ntlm_version = ntlm_message_type(ah_data[1]);
if (ntlm_version instanceof Error) {
options.debug(options.prefix, ntlm_version.stack);
return options.badrequest(request, response, next);
}
if (ntlm_version === 1) {
return handle_type1(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
if (ntlm_version === 3) {
if (cache.get_proxy(request.connection.id) !== null) {
return handle_type3(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
options.debug(options.prefix, 'Unexpected NTLM message Type 3 in new connection for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.internalservererror(request, response, next);
}
options.debug(options.prefix, 'Type 2 message in client request');
return options.badrequest(request, response, next);
};
};
my response is
{"DomainName":"ijk","UserName":"xyz","Password":"","Workstation":"some","Authenticated":true}

How to check if database entry (table row) already exists

I am trying to check whether a table entry exists in a database, but what I have so far always returns true even if there is no entry. What am I doing wrong?
Thank you all.
This will always console.log >>>> true
let myPersLocalEntityExistsPromise = function (localEntityGUID) {
return new Promise(function (resolve, reject) {
let myEntityExists = true;
const client = myDb.mySQLDbLocalConnection();
let stmt = "SELECT EXISTS(SELECT 1 FROM MY_ENTITY_TABLE WHERE LOCAL_MY_ENTITY_GUID = ?)";
let todo = [
localEntityGUID
];
client.query(stmt, todo, function (err, row) {
if (err) {
return ("myPersLocalEntityExists: " + err.message);
} else {
if (row && row.length) {
console.log(localEntityGUID + ' Case row was found!');
} else {
myEntityExists = false;
console.log(localEntityGUID + ' Case row was NOT found!');
}
}
});
client.end(function (err) {
if (err) {
console.log('ERRR');
}
});
if (myEntityExists) {
resolve(myEntityExists);
} else {
reject(myEntityExists);
}
})
}
function myPersLocalEntityExists(localEntityGUID, callback) {
let responsePromises = []
responsePromises.push(myPersLocalEntityExistsPromise(localEntityGUID))
Promise.all(responsePromises).then(fromResolve => {
console.log(">>>> " + fromResolve);
return fromResolve;
}).catch(fromReject => {
console.log(">>>> " + fromReject);
return fromReject;
});
}

JavaScript Global Variable Not Updating Value

I have the below JavaScript code to develop an app in Fuse Tools. There is one last error that I cannot seem to understand and that is that my variable b64data should be a global variable and is not updating it's value from the capturePhoto function and letting me send the updated value in the submitPhoto function to the server. It should send the base64 encoded value as the picture variable in my POST function. Any help is appreciated!
var Observable = require("FuseJS/Observable");
let ImageTools = require("FuseJS/ImageTools");
var FileSystem = require("FuseJS/FileSystem");
var Base64 = require("FuseJS/Base64");
var Camera = _camera;
var b64data;
var captureMode = Observable();
var flashMode = Observable();
function getCameraInfo() {
Camera.getCameraInfo()
.then(function(info) {
console.log("captureMode: " + info[Camera.INFO_CAPTURE_MODE]);
console.log("flashMode: " + info[Camera.INFO_FLASH_MODE]);
console.log("cameraFacing: " + info[Camera.INFO_CAMERA_FACING]);
console.log("supportedFlashModes: " + info[Camera.INFO_SUPPORTED_FLASH_MODES].join());
captureMode.value = info[Camera.INFO_CAPTURE_MODE];
flashMode.value = info[Camera.INFO_FLASH_MODE];
if (Camera.INFO_PHOTO_RESOLUTIONS in info) {
var availableResolutions = info[Camera.INFO_PHOTO_RESOLUTIONS];
availableResolutions.forEach(function(e) {
console.log(e.width + "x" + e.height);
});
photoResolution = availableResolutions[Math.floor(availableResolutions.length * 0.4)];
var options = {};
options[Camera.OPTION_PHOTO_RESOLUTION] = photoResolution;
Camera.setPhotoOptions(options)
.then(function() {
console.log("New photo options set: " + JSON.stringify(options));
})
.catch(function(error) {
console.log("Failed to set photo options: " + error);
});
}
})
.catch(function(err) {
console.log("Failed to get camera info: " + err);
});
}
getCameraInfo();
function nextFlashMode() {
if (flashMode.value == Camera.FLASH_MODE_AUTO) return Camera.FLASH_MODE_ON;
else if (flashMode.value == Camera.FLASH_MODE_ON) return Camera.FLASH_MODE_OFF;
else if (flashMode.value == Camera.FLASH_MODE_OFF) return Camera.FLASH_MODE_AUTO;
else throw "Invalid flash mode";
}
function setCaptureMode(cm) {
Camera.setCaptureMode(cm)
.then(function(mode) {
captureMode.value = mode;
console.log("Capture mode set to: " + mode);
})
.catch(function(err) {
console.log("Failed to set capture mode: " + err);
});
}
function capturePhoto() {
Camera.capturePhoto()
.then(function (photo) {
photo.save()
.then(function(filePath) {
console.log("Photo saved to: " + filePath);
var arrayBuff = FileSystem.readBufferFromFileSync(filePath);
var b64data = Base64.encodeBuffer(arrayBuff); // send this to the backend
photo.release();
})
.catch(function(error) {
console.log("Failed to save photo: " + error);
photo.release();
});
})
.catch(function (error) {
console.log("Failed to capture photo: " + error);
});
}
var isRecording = Observable(false);
var recordingSession = null;
function startRecording() {
isRecording.value = true;
Camera.startRecording()
.then(function (session) {
recordingSession = session;
})
.catch(function (error) {
console.log("Failed to start recording: " + error);
isRecording.value = false;
});
}
function stopRecording() {
isRecording.value = false;
recordingSession.stop()
.then(function (recording) {
router.push("VideoPage", recording.filePath());
})
.catch(function (error) {
console.log("Failed to stop recording: " + error);
});
recordingSession = null;
}
var cameraBack = true;
function flipCameraFacing() {
var front = Camera.CAMERA_FACING_FRONT;
var back = Camera.CAMERA_FACING_BACK;
Camera.setCameraFacing(cameraBack ? front : back)
.then(function (newFacing) {
cameraBack = newFacing == back;
getCameraInfo();
console.log("Camera facing set to: " + (newFacing == back ? "back" : "front"));
})
.catch(function (err) {
console.log("Failed to set camera facing: " + err);
});
}
function changeFlashMode() {
Camera.setFlashMode(nextFlashMode())
.then(function(newFlashMode) {
flashMode.value = newFlashMode;
console.log("Flash mode set to: " + flashMode.value);
})
.catch(function(err) {
console.log("Failed to set flash mode: " + err);
});
}
var name = Observable();
var email = Observable();
var market = Observable();
module.exports = {
name: name,
email: email,
market: market,
b64data: b64data,
submitPhoto: submitPhoto,
captureMode: captureMode,
setCaptureModePhoto: function () { setCaptureMode(Camera.CAPTURE_MODE_PHOTO); },
setCaptureModeVideo: function () { setCaptureMode(Camera.CAPTURE_MODE_VIDEO); },
capturePhoto: capturePhoto,
startRecording: startRecording,
stopRecording: stopRecording,
isRecording: isRecording,
flipCameraFacing: flipCameraFacing,
flashMode: flashMode,
changeFlashMode: changeFlashMode,
}
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
May be because of you are declaring b64data again in capturePhoto function on line 72 in your shared code.
try
b64data = ...
instead of
var b64data = ...

Remove name file html from url

I am using Angular JS for my Front End and Express Server for backend.
I am trying to remove the init.html from my url.
I have read other post and I have not managed to fix it.
Now : http://localhost:3000/init.html#!/export
I want look like : http://localhost:3000/#!/export
I tried : $locationProvider.hashPrefix() and
locationProvider.html5Mode(true) but it is not working.
manager-app.js
angular.module("ManagerApp", ["angularUtils.directives.dirPagination", "ngRoute"]).config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index.html"
})
.when("/export", {
templateUrl: "export/listExport.html",
controller: "ListCtrlExport"
});
index.html is a static html
init.html
<html ng-app="ManagerApp">
<head>
<title>
ManagerApp
</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" type="text/css" />
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="/bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script type="text/javascript" src="/bower_components/bootbox.js/bootbox.js"></script>
<script type="text/javascript" src="/manager-app.js"></script>
<script type="text/javascript" src="/export/list-ctrl.js"></script>
<script type="text/javascript" src="/export/edit-ctrl.js"></script>
</head>
<body>
<ng-view></ng-view>
</header>
</body>
</html>
index.js
var express = require("express");
var bodyParser = require("body-parser");;
var helmet = require("helmet");
var path = require('path');
var app = express();
var folder = path.join(__dirname, '/public');
var MongoClient = require('mongodb').MongoClient;
var mURL = "mongodb://XXXXXXXXXXXXXXXXXxXXXXXXXX";
var port = (process.env.PORT || 10000);
var BASE_API_PATH = "/api/v2";
var moduleExport = require("./api/v2/exportModule.js");
var dbAlberto;
var dbUser;
app.use("/", express.static(path.join(__dirname, "public")));
app.use(bodyParser.json()); //use default json enconding/decoding
app.use(helmet()); //improve security
app.use("/",express.static(path.join(__dirname, 'public')));
app.use("/api/v2/tests", express.static(path.join(__dirname , "public/test.html")));
MongoClient.connect(mURL, {
native_parser: true
}, function(err, database) {
if (err) {
console.log("CANNOT connect to database" + err);
process.exit(1);
}
dbAlberto = database.collection("exports");
dbUser = database.collection("user");
moduleExport.register(app, dbAlberto, dbUser, BASE_API_PATH);
app.listen(port, () => {
console.log("Magic is happening on port " + port);
});
});
exportModule
var exports = module.exports = {};
exports.register = function(app, dbAlberto, dbUser, BASE_API_PATH) {
// Authentication apikey
var key = function(request, callback) {
var d;
dbUser.find({
apikey: request
}).toArray(function(err, sExport) {
if (sExport.length > 0) {
d = 1;
}
else {
d = 0;
}
callback(d);
});
}
function searchFrom(sExport,from,to){
var from = parseInt(from);
var to = parseInt(to);
var res=[];
sExport.forEach((filt)=>{
if(filt.year>=from && filt.year<=to){
res.push(filt);
}
});
return res;
// GET a collection and Search
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
var url = request.query;
var province = url.province;
var year = url.year;
var importS = url.importS;
var exportS = url.exportS;
var off = 0;
var limite = 100;
var res = request.query.apikey;
var from = url.from;
var to = url.to;
var resul = key(res, function(d) {
if (d > 0) {
if (url.limit != undefined) {
limite = parseInt(url.limit);
off = parseInt(url.offset);
}
if (from != undefined && to != undefined) {
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
var filted=searchFrom(sExport,from,to);
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
else {
dbAlberto.find({}).skip(off).limit(limite).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var filted = sExport.filter((stat) => {
if ((province == undefined || stat.province == province) && (year == undefined || stat.year == year) && (year == undefined || stat.year == year) && (importS == undefined || stat.importS == importS) && (exportS == undefined || stat.exportS == exportS)) {
return stat;
}
});
if (filted.length > 0) {
console.log("INFO: Sending stat: " + JSON.stringify(filted, 2, null));
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
// LoadInitialData
app.get(BASE_API_PATH + "/export-and-import/loadInitialData", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
dbAlberto.find({}).toArray(function(err, stats) {
if (err) {
console.error('WARNING: Error while getting initial data from DB');
return 0;
}
if (stats.length === 0) {
var initialStats = [{
"province": "jaen",
"year": "2013",
"oil": "375",
"importS": "802",
"exportS": "274"
}];
dbAlberto.insert(initialStats);
console.log("Date insert in db");
response.sendStatus(201, BASE_API_PATH + "/");
}
else {
console.log('INFO: DB has ' + stats.length + ' objects ');
response.sendStatus(200);
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
/*
// GET a collection
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
console.log("INFO: New GET request to /export-and-import");
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
console.log("INFO: Sending export and import stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
});
});
*/
// GET a single resource
app.get(BASE_API_PATH + "/export-and-import/:province", function(request, response) {
var province = request.params.province;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import-stats/" + province);
dbAlberto.find({
province: province
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//GET all stats of one year
app.get(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import/ without province, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import/" + province);
dbAlberto.find({
province: province,
year: year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province + " and " + year);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a collection
app.post(BASE_API_PATH + "/export-and-import", function(request, response) {
var newStats = request.body;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!newStats) {
console.log("WARNING: New POST request to /export-and-import without stats, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New POST request to /export-and-import with body: " + JSON.stringify(newStats, 2, null));
if (!newStats.province || !newStats.year || !newStats.oil || !newStats.importS || !newStats.exportS) {
console.log("WARNING: The stat " + JSON.stringify(newStats, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: newStats.province,
year: newStats.year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var sExportBefore = sExport.filter((result) => {
return (result.province.localeCompare(newStats.province, "en", {
'sensitivity': 'base'
}) === 0);
});
if (sExportBefore.length > 0) {
console.log("WARNING: The contact " + JSON.stringify(newStats, 2, null) + " already extis, sending 409...");
response.sendStatus(409); // conflict
}
else {
console.log("INFO: Adding contact " + JSON.stringify(newStats, 2, null));
dbAlberto.insert(newStats);
response.sendStatus(201); // created
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a single resource
app.post(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New POST request to /export-and-import-stats/" + province + " and " + year + ", sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a collection
app.put(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New PUT request to /export-and-import-stats, sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a single resource
app.put(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var updateExp = request.body;
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!updateExp) {
console.log("WARNING: New PUT request to /export-and-import-stats/ without contact, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New PUT request to /export-and-import-stats/" + province + " with data " + JSON.stringify(updateExp, 2, null));
if (!updateExp.province || !updateExp.year || !updateExp.oil || !updateExp.importS || !updateExp.exportS || updateExp.province !== province || updateExp.year !== year) {
console.log("WARNING: The contact " + JSON.stringify(updateExp, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: province,
$and: [{
year: year
}]
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
dbAlberto.update({
province: province,
year: year
}, updateExp);
console.log("INFO: Modifying contact with name " + province + " with data " + JSON.stringify(updateExp, 2, null));
response.send(updateExp); // return the updated contact
}
else {
console.log("WARNING: There are not any stats with provinc " + province);
response.sendStatus(404); // not found
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a collection
app.delete(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("INFO: New DELETE request to /export-and-import-stats");
dbAlberto.remove({}, {
multi: true
}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: Remove: " + n + " stats, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a single resource
app.delete(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province || !year) {
console.log("WARNING: New DELETE request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New DELETE request to /export-and-import-stats/" + province + " and " + year);
dbAlberto.remove({
province: province,
year: year
}, {}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: The stat with name " + province + " and year " + year + " has been succesfully deleted, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
}
Thanks in advance !

How to update specific property in whole database in MongoDB?

I want to update a property in whole database.
Example I want to update property name if name=='Gaurav' then I want to replace this as name='gsb' in all documents in all collections, whether it is nested objects property. Is there any way to do this without knowing the structure of document, cause in each collection documents are of different structure. I want this query for Node JS.
What I tried is as follows. I am stuck in between.
var MongoClient = require('mongodb').MongoClient;
var config = require('../config.js');
var async = require('async');
_ = require ('lodash');
MongoClient.connect('mongodb://' + config.db_url + '/' + config.db_name, function(err, db) {
if(err) throw err;
db.listCollections().toArray(function(err, collInfos) {
async.each(collInfos,function(collectionDetails,cb){
db.collection(collectionDetails.name,function(err, collection){
if(err){
console.log(err)
}
else
{
collection.find().toArray(function(error, result) {
if(error) {
console.log(error);
}
else {
_depthFirstSearch = (collection, input) => {
let type = typeof collection;
if (type === 'string' || type === 'number' || type === 'boolean') {
return _.includes(collection.toString().toLowerCase(), input.toString().toLowerCase());
}
return _.some(collection, (item) => this._depthFirstSearch(item, input));
}
var data= _.filter(result, (item) => {
return _depthFirstSearch(item, "Gaurav");
});
console.log(data)
}
});
}
})
cb();
})
});
});
I found the solution after lots of brainstorm. I wrote below function to achieve this.
var replaceAllInsatnceInDB=function(db_url/*localhost:27017*/,db_name,propName,stringToSearch,stringToReplace){
MongoClient.connect('mongodb://' + db_url + '/' + db_name, function(err, db) {
if(err) throw err;
db.listCollections().toArray(function(err, collInfos) {
async.each(collInfos,function(collectionDetails,cb){
db.collection(collectionDetails.name,function(err, collection){
if(err){
console.log(err)
}
else
{
collection.find().toArray(function(error, result) {
if(error) {
console.log(error);
}
else {
result.forEach(function(document){
var op=function(record){
if(record!== null && record!==undefined ){
var props=Object.keys(record);
var forObject=function(obj){
if(Array.isArray(obj)){
var forArray=function(arr){
for(var j=0;j<arr.length;j++){
if(typeof arr[j] ==="string"){
if(arr[j]===stringToSearch && props[i]==propName){
arr[j]=stringToReplace
}
}
if(typeof arr[j] ==="object"){
forObject(arr[j]);
}
}
return(arr)
}
obj=forArray(obj)
}else{
op(obj);
}
return(obj);
}
for(var i=0;i<props.length;i++){
if(typeof record[props[i]] ==="string"){
if(record[props[i]]===stringToSearch && props[i]==propName){
record[props[i]]=stringToReplace
console.log()
}
}
if(typeof record[props[i]] ==="object"){
record[props[i]]=forObject(record[props[i]])
}
}
}
return(record);
}
document=op(document);
collection.update({_id : document._id},document,function(error,doc){
if(error){
console.log(error)
}else{
console.log("template updated");
}
})
})
}
});
}
})
cb();
})
});
});
}

Categories