req.params not working in mongoose findOne - javascript

I have this function which passes a parameter
fetchprofile() {
let uri = "http://localhost:4000/data/username/" + this.tintin;
this.axios.post(uri).then(response => {
this.fname = response.data.fname;
this.lname = response.data.lname;
});
}
And this is the route:
adnmastroutes.route('/username/:usertin').post(function (req, res) {
console.log('TIN No. of user is:' + req.params.usertin);
adnmastmainmodel.findOne({tin: req.params.usertin}, function (err, user) {
if (err) {
console.log(err);
}
else {
console.log(user);
res.json(user);
} }); });
Now in the line
console.log('TIN No. of user is:' + req.params.usertin);
the passed parameter req.params.usertin has a value.
BUT WHY IS IT IN THE LINE
adnmastmainmodel.findOne({tin: req.params.usertin}, function (err, user) {
the passed parameter req.params.usertin ha NO value.
(the line:
adnmastmainmodel.findOne({tin: req.params.usertin}, function (err, user) {
returns a null response. But when I changed it this way:
adnmastmainmodel.findOne({tin: '012349876'}, function (err, user) {
it returns the desired response.)
PLEASE HELP HOW WILL I RESOLVE THIS?
p.s. The value of the parameter this.tintin came from sessionStorage.getItem

Make sure parameter is string by using the toString() function
adnmastmainmodel.findOne({tin: req.params.usertin.toString() }, function (err, user)

Related

boolean from function is returning undefined node.js

I have 2 functions... 1st one in auth.js, which does this:
const adminCheck = (req, res) => {
console.log(“one”)
UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
return true
} else {
return false
}
})
}
module.exports = {
adminCheck
}
basically checks if the user is an admin in my table. that works, but I am trying to retrieve the boolean in my function in my index.js function, which is below.
router.get(‘/viewRegistration’, auth.ensureAuthenticated, function(req, res, next) {
console.log("authcheck: " + auth.adminCheck())
const user = JSON.parse(req.session.passport.user)
var query = “SELECT * FROM tkwdottawa WHERE email = ‘” + user.emailAddress + “’”;
ibmdb.open(DBCredentials.getDBCredentials(), function (err, conn) {
if (err) return res.send(‘sorry, were unable to establish a connection to the database. Please try again later.’);
conn.query(query, function (err, rows) {
if (err) {
Response.writeHead(404);
}
res.render(‘viewRegistration’,{page_title:“viewRegistration”,data:rows, user});
return conn.close(function () {
console.log(‘closed /viewRegistration’);
});
});
});
})
where I am logging the value in the console.log right under where I initialize the function, it is returning undefined. how can I fix this?
You need to use Promise and wrap all callbacks to actually return a given result value from a function that uses a callback because usually a callback is called asynchronously and simply returning a value from it does not help to catch it in a calling function.
const adminCheck = (req, res) => {
console.log(“one”)
return new Promise(resolve, reject) => {
UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
resolve(true)
} else {
resolve(false)
}
})
}
});
then you need to await a result calling this function using await keyword and marking a calling function as async:
router.get(‘/viewRegistration’, auth.ensureAuthenticated, async function(req, res, next) {
console.log("authcheck: " + await auth.adminCheck())
const user = JSON.parse(req.session.passport.user)
var query = “SELECT * FROM tkwdottawa WHERE email = ‘” + user.emailAddress + “’”;
ibmdb.open(DBCredentials.getDBCredentials(), function (err, conn) {
if (err) return res.send(‘sorry, were unable to establish a connection to the database. Please try again later.’);
conn.query(query, function (err, rows) {
if (err) {
Response.writeHead(404);
}
res.render(‘viewRegistration’,{page_title:“viewRegistration”,data:rows, user});
return conn.close(function () {
console.log(‘closed /viewRegistration’);
});
});
});
})
That's simple. You just forgot to return the inner function's return value
const adminCheck = (req, res) => {
console.log(“one”)
return UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => {
if(response) {
return true
} else {
return false
}
})
}
module.exports = {
adminCheck
}

Node.js query INSERT callback not working as expected

Small problem when using POST and adding an INSERT. Works as below, but want to use a callball after the data has been inserted. At the moment the database is being updated. (good) but can't use the callback - I would expect this to be just below the throw error. So you could use result.insertId. Any thoughts welcome?
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if (error)throw error;
//*** when I add response here get 502 bad gateway error.
});
res.sendStatus(200);
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
res.sendStatus(error);
});
});
try this way :
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if(error){
return res.status(500).send(error);
}
if(!error && results){
return res.status(200).send(results);
}
});
});
}).catch(function(error) {
return res.status(500).send(error);
});
});
if you want to use callback then ,create a separate function like :
var insertData = function(query,data,callback){
db.query(query, data, function (error, results, fields) {
if(error){callback(error,null);}
if(!error && results){callback(null,results);}
});
});
and call this way inside getID :
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
insertData('INSERT INTO cu_groups SET ?', post, function (error,data){
if(error){
return res.status(500).send(error);
}
if(data){
return res.status(200).send(data);
}
});
});
Working code below many thanks to Saurabh Mistry. I removed the SET post and added the table fields and values explicity.
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
// query
let query = "INSERT INTO cu_groups (ID, name) VALUES('" + ID + "','" + name + "')";
// execute query
db.query(query, (error, result) => {
if(error){
return res.status(500).send(error);
}
if(!error && result ){
return res.send(result);
}
});
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
return res.status(500).send(error);
});
});

Mongoose.statics: 'findOne is not a function' + 'create is not a function', confusion over different call types

I have a shopping cart model that needs a method to retrieve or create the current users cart.
I was moving a working version from controller to model.statics and ran into some confusion about how to call the findOne and create methods of the model from within the static function.
I found answers to my problems in these two posts mongooge-model-findone-typeerror-object-has-no-method-findone and mongoose-typeerror-on-a-models-findone-method
Essentially my original call to
CartSchema.findOne({ userId: userId }, function (err, cart)
was fixed by changing to
this.findOne({ userId: userId }, function (err, cart)
but the same technique did NOT work for the create function, instead my original call to
CartSchema.create(cart, function (err, newCart)
was fixed using a different style
mongoose.model('Cart').create(cart, function (err, newCart)
Here is the working code plus comments for what was in place and the exceptions that were thrown
CartSchema.statics.getMyCart = function (userId, callback) {
try {
// CartSchema.findOne({ userId: userId }, function (err, cart)
// will throw
// TypeError: CartSchema.findOne is not a function
//
// this.findOne({ userId: userId }, function (err, cart)
// OK
this.findOne({ userId: userId }, function (err, cart) {
if (err) {
return callback(err, null, false);
}
if (cart) {
// If cart exists for this user, then execute callback for additional actions against this cart
return callback(null, cart, false);
}
cart = {
userId: userId,
items: []
};
// CartSchema.create(cart, function (err, newCart) {
// will throw
// TypeError: CartSchema.create is not a function
//
// this.create(cart, function (err, newCart) {
// will throw
// TypeError: this.create is not a function
mongoose.model('Cart').create(cart, function (err, newCart) {
if (err) {
return callback(err, null, false);
}
// Cart has been created for this user, now execute callback for additional actions against this cart
return callback(null, newCart, true);
});
});
} catch (e) {
l.exception(e);
}
}

sqlite3 callbacks (node.js)

I'm trying to compare an entered email on my website, to ones in the database to see whether it already exists. If it does, then the function returns false and an error is displayed.
var db = new sqlite3.Database('users_db.db');
db.get(
"SELECT * FROM users WHERE useremail = ?",
[email],
function (err, rows) {
if (rows == undefined ){
global.returnvalue2 = false;
}
}
);
What I want is for the function to be run immediately after the selection, so that the returned value is false, and the user record is not created.
At the moment I realise that the callback is being called after everything, so its just making the selection and carrying on throughout the rest of the program until the end.
How can I check if there are any existing records with the same email?
Make use of the async features in javascript, so your code would look something like this;
var db = new sqlite3.Database('users_db.db');
function checkemail(email, cb) {
db.get(
"SELECT * FROM users WHERE useremail = ?",
[email],
function (err, rows) {
if (err || rows == undefined ){
cb("bad email", null)
} else {
cb(null,rows)
}
});
}
function checkpassword(pw,cb) {....}
function checkclass(cls,cb) {....}
and then write you code like this;
checkemail(myemail, function(err,rows) {
if (err) return alert(err);
checkpassword(pw, function(err, msg) {
if (err) return alert(err);
checkclass(cls, function(err, msg) {
if (err) return alert(err);
alert("Congratulation you passed all the checks");
});
});
});
Here's a little one I made.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('iHacks.db');
function get_user_credentials (email, password)
{ return new Promise((rs, rj) => {
function callback (err, User)
{
if (err) rj(err);
rs(User);
}
db.get('select * from users where email=? and password=?', [email, password], callback);
}); }
function login (email, password)
{ return new Promise ((rs, rj) => {
// Hashing the password.
password = sha256(password + 'EzSalt');
// Creating an Error
const err = new Error('Email or password did not match!');
// Callback functions
function check (User)
{
rs(User);
}
function fail (err)
{
rj(err);
}
// Getting the user credentials
get_user_details(email, password).then(check).catch(fail);
}); }
login()
.then(/* Continue code */)
.catch(err => {throw new Error(err); })
;

Node.js moongoose database count undefined

I have the following function in one of my mongoose models:
UserSchema.methods.checkUsernameExists = function checkUsernameExists(req){
User.count({ username: req.body.username }, function(err, count){
if(err){
return console.error(err);
}
console.log(count); //Logs 2
});
}
Now when I log it, it gives the correct count. But if I return the count and try doing this, in one of my controllers it returns undefined.
var User = require("../models/user").User;
var user = new User();
exports.signup = function(req, res){
var count = user.checkUsernameExists(req);
console.log(test)
}
Any help would be appreciated thank you.
Remember that Node works asynchronously, meaning that you can't return a normal value from a function that executes an asynchronous function itself, like your checkUsernameExists does.
The most common way to deal with this is by passing a callback function which is called when the value is retrieved:
UserSchema.methods.checkUsernameExists = function checkUsernameExists(req, callback) {
User.count({ username: req.body.username }, callback);
};
This will pass the err and count variables that are the result of User.count as arguments to the callback function you supply. To use:
user.checkUsernameExists(req, function(err, count) {
if (err) {
console.error(err);
} else {
console.log('the count is', count);
}
});
To make the function to what it's name suggests, namely to 'return' a boolean to signify if a username already exists, you might use something like this:
UserSchema.methods.checkUsernameExists = function checkUsernameExists(req, callback) {
User.count({ username: req.body.username }, function(err, count) {
if (err) {
callback(err);
} else {
callback(null, count !== 0);
}
});
};

Categories