I am trying to check if a user already exists in the database, I have managed to stop creating a user if one already exists with the same phone number , however I do not seem to get the error message displayed. I am not too sure why my error is not being handled correctly. Here is my code:
exports.usercreate = function (req, res)
{
users.create(req.body, function (err, result)
{
var phonenumber = req.body.phonenumber;
console.log(phonenumber);
if (phonenumber.length > 0)
{
res.status(200).json(
{
status: "error",
resCode: 400,
msg: 'cutomer added error'
});
}
else
{
res.status(200).json(
{
status: "success",
resCode: 200,
msg: "users Added Successfully",
});
}
else
{
console.log(error)
}
});
};
Getting error like customer added error. but records are inserted in couchbase
as #TommyBs mentioned, you are basically comparing an N1qlQuery object to whatever is coming on req.body.phonenumber
...
bucket.query(query, function(err, rows, meta) {
for (row in rows) {
if(row.phonenumber == req.body.phonenumber) {
res.status(500).json({status:"error", resCode: 500, msg:"users Already exist"});
}
}
}
Related
I am newbie with JavaScript, NodeJS and Express. I writing simple application which does the following
User makes a request.
Server makes mulitple rest calls and renders the response.
How can I make sure that all the calls are complete and I create an object that I can send to the user? I saw people said something about async.parallel. Is that the only way to go? Any examples would help.
You can use promises to run code in sequence.
Here is an example (a little scaled down) of a login functionality I made using promises.
In a module named LoginController I have placed this piece of code.
this.attemptLogin = function(body, res) {
var reason = "";
var user = null;
loginM.findUser(body.username)
.then(function(result) {
if (result.status) {
user = result.result[0];
return this.verifyPassword(body.password, result.result[0].Password);
} else {
reason = {status: false, message: "Incorrect username", result: null};
throw(reason);
}
})
.then(function(result) {
if (result.message) {
res.send({status: true, message: "Successfully logged in", result: user});
return;
} else {
reason = {status: false, message: "Incorrect password", result: null};
throw(reason);
}
}).catch(function(err) {
res.send(err);
});
}
And in another module named LoginModel (LoginM) I have placed this code
this.findUser = function(username, email) {
return new Promise(function (resolve, reject) {
pool.getConnection(function (err, connection) {
if (err) {
reject({status: false, message: err});
} else {
connection.query('select Id, Name, Email, Password from Users ' +
'where (Users.Name = ? OR Users.Email = ?) AND Removed = 0 LIMIT 1', [username, email], function (err, rows) {
connection.release();
if (!err) {
if(rows.length > 0) {
resolve({status: true, message: "Found user", result: rows});
}
else
resolve({status: false, message: null})
} else {
reject({status: false, message: err});
}
});
}
});
});
}
And a similar method for verifyPassword which also returns a promise.
Now, the things to note are that:
the code inside every then is run asynchronously
the then parts are executed in order, i.e, you won´t enter the next then until you have returned something from the previous then
whatever you resolve from the methods returning promises (findUser and verifyPassword) are passed as the variable named result in .then(function(result)
I have this table with a clob column. I connect to the database from my express app using the oracledb driver. I want to print out this clob. This is my code:
router.get('/:task_name', function (req,res) {
"use strict";
oracledb.getConnection(connAttrs.database, function (err, connection) {
if (err) {
// Error connecting to DB
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error connecting to DB",
detailed_message: err.message
}));
return;
}
connection.execute("select solution from solvedtasks s join tasks t on t.TASK_ID = s.TASK_ID WHERE task_name= :task_name", [req.params.task_name],{
outFormat: oracledb.OBJECT //resultSet:true,
}, function (err, result) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting the user profile",
detailed_message: err.message
}));
} else {
res.contentType('application/json').status(200);
res.send(JSON.stringify(result.rows[0]));
console.log(result.rows[0]);
// fetchRowsFromRS(connection,res,result.resultSet,10);
}
// Release the connection
connection.release(
function (err) {
if (err) {
console.error(err.message);
} else {
console.log("GET /SolvedTasks : Connection released");
}
});
});
});
});
Instead of printing the clob from my database I get something that looks like lob metadata. Has anyone else encountered this issue? Here is a screenshot of my output:
So I solved this, I am posting an answer in case anyone has this problem. Apparently the original oracledb driver has some issues handling clobs. But there is a library that enhances its functionality, called simple-oracledb, very easy to use and install: https://github.com/sagiegurari/simple-oracledb
by using connection.query, clobs are properly handled:
enter code here
connection.query('SELECT * FROM departments WHERE manager_id > :id', [110], {
splitResults: true, //True to enable to split the results into bulks, each bulk will invoke the provided callback (last callback invocation will have empty results)
bulkRowsAmount: 100 //The amount of rows to fetch (for splitting results, that is the max rows that the callback will get for each callback invocation)
}, function onResults(error, results) {
if (error) {
//handle error...
} else if (results.length) {
//handle next bulk of results
} else {
//all rows read
}
});
I have an insert code inside of my tables in my Mobile Service in Azure, and I want to know if there is a better way to get the name of the current table my insert script is.
Today the code of my table "ClientTest1" look like this:
function insert(item, user, request) {
var payload = {
data: {
msg: "Nivel: " + item.Nivel
}
};
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.gcm.send("ClientTest1", payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
},
error: function(err) {
console.log("request.execute error", err)
request.respond();
}
});
}
I would like to have a code like this:
function insert(item, user, request) {
var payload = {
data: {
msg: "Nivel: " + item.Nivel
}
};
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.gcm.send(tables.current.name, payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
},
error: function(err) {
console.log("request.execute error", err)
request.respond();
}
});
}
I would like to not need hard code each name of the table in the "tag" parameter for my push.
Does anyone know a better way to do this? Thanks
You can use the current property of the tables global object, and that will return you the current table. So you can use this for the table name:
var tableName = tables.current.getTableName();
I have a form and when something doesn't go right after submission, I want to be able to give the user specific error messages. I am using Sequelize as my ORM, and the promises returned are getting a bit messy with all the nested code.
For instance, if we have two models to update: User and Photo:
models.User.find({where: {name: 'bob' }}).then(function(user) {
if(user) {
user.updateAttributes({email: email}).then(function(user) {
models.Photo.find({where: { hash: hash}}).then(function(photo) {
if(photo)
res.json({"message":"updated"});
else
res.status(404).json({"error": "Could not find Photo"});
}).catch(err) {
res.status(500).json({"error": err});
});
}).catch(function(err) {
res.status(500).json({"error": err});
});
} else {
res.status(404).json({"error": "Could not find user"});
}
}).catch(function(err) {
res.status(500).json({"error": err});
});
And if I have 10 fields in the form to update, all the nested code can become overbearing.
What recommendations can be given if I wish to have specific error descriptions, but also more readable code? Would it be possible to capture all the 404 and 500 errors in one code block instead of breaking them up like I have?
You can make use of promise chaining and a helper method to reduce your code to a series of 3 .thens and a single .catch:
function notFoundError(model) {
var e = new Error('Could not find ' + model);
e.statusCode = 404;
throw e;
}
models.User
.find({where: {name: 'bob'}})
.then(function (user) {
if (user) {
return user.updateAttributes({email: email});
} else {
notFoundError('user');
}
})
.then(function (user) {
return models.photos.find({where: {hash: hash}});
})
.then(function (photo) {
if (photo)
res.json({"message": "updated"});
else
notFoundError('photo');
})
.catch(function (err) {
if (err.statusCode) {
res.status(err.statusCode);
} else {
res.status(500);
}
res.json({'error': err.message});
});
When the following route is called in express, it is actually executed 6 times. The console.log is printed 6 times, and my mongoose logic is executed 6 times (saves 6 time in database).
I then get returned a http 500 from cloud9ide "Could not proxy request". I am really confused, I have no loops in my code, how can this happen? The console.log("in else (2)"); get printed 6 times.
Edit: I have tried the mongooseLogic code with various parts commented out, and the issue was still there. This looks like it isn't a mongoose issue.
Second edit: I have changed the post for get and hardcoded the body that would be sent, and the route was executed only once.
Third edit: I am also using everyauth for session/authentication with the facebook oauth.
app.post("/result/:userId/:elementId", function(req, res) {
var receivedJSON = req.body;
console.log("In route");
//Making sure the receive request is valid
if(typeof(receivedJSON.type) !== undefined) {
mongooseLogic.saveResults(req.params.elementId, receivedJSON, req.params.userId, function(message) {
if(message === "Success") {
res.json({ success: true, message: 'Result saved.'});
}
else {
res.json({ success: false, message: 'Error in saving results. Trace: ' + message});
}
});
}
else {
res.json({ success: false, message: 'Failed, Invalid object sent to server'});
}
});
Code on the mongooseLogic file:
var saveResults = function(elementRefId, receivedResult, userId, callback){
if(elementRefId.toString().length !== 24 ){
callback("Invalid objectId for elementId");
}
else{
Result.findOne({ "id" : userId, "serieResult.id": elementRefId }, function(err, result){
if(err){
callback("No Document found: " + err);
}
else if( result === null){
console.log("in null");
var tempResult = {
id : elementRefId,
unit : receivedResult.unit,
value : receivedResult.value
}
Result.update({ "id" : userId}, { $push: {"serieResult": tempResult}}, {upsert: true}, function(err){
if(err){
callback("Error in saving result (Distance): " + err);
}
else{
callback("Success");
}
});
}
else{
Result.update({ "id" : userId, "serieResult.id": elementRefId },
{ $set:{
"serieResult.$.unit" : receivedResult.unit,
"serieResult.$.value" : receivedResult.value,
},{upsert: true}, function(err){
if(err){
callback("Cant update doc: " + err);
}
else{
console.log("in else (2)");
callback("Success");
}
});
}
});
}
}
}
This was a problem with the Cloud9 proxy that interfered. The problem was adressed thanks to this issue and has been resolved.