i am accepting username and phone from the front end and now i need to send phone to mongodb and based on that phone i need to get the details of a matching student's detail.Please help me to achieve this.
this is my server code:
server.post('/phone',urlencodedParser,function(req,res){
var resp={
Username : req.body.username,
phn:req.body.password
}
databaseInterface.studentDetail(resp.phn);
res.json(resp.phn);
console.log(resp);
res.send('username :' + req.body.username + 'passwrd:' + req.body.password);
})
this is my mongoDB code:
function studentDetail(phn){
User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
if (err) return phn(err);
return phn(null, studentcollection2);
}).select('-__v');
}
The callback that you are using has some problem.
function studentDetail(phn,callback){
User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
if (err) return callback(err);
return callback(null, studentcollection2);
}).select('-__v');
}
for ur response,
databaseInterface.studentDetail(resp.phn, function(err, val){
if(err) res.send('ERROR!');
else res.send('Response');
});
Not Tested!
FindOne will return a promise. You need to wait for it to be fulfilled before returning your json.
To achieve that, you need to do the following:
databaseInterface.studentDetail(resp.phn).then((data,error) => {
res.json({response:data});
});
Your query seems wrong too.
function studentDetail(phone) {
return [yourQuery].exec()
}
I believe that's it
Related
What does it do?
In the documentation, I do not understand the answer.
I'm not using it correctly, I get a query error from the database
pool.connect(function (err, client, done) {
if (err) console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";', function (err, result) {
if (err) {
console.log("query " + err.toString());
}
else {
console.log(result.rows);
//module.exports.res = result.rows;
}
done();
});
});
Now there are many errors, the error you are getting from the database (sad that you don't share it with us) should be the "dateColloquy"FROM part. Now once you fixed that and inserted a space before FROM, you'll notice that all your fields are not included as data, but exactly as what you wrote - idName (literally the string), ... for every field but id the same.
Use backticks (```) (or nothing at all) for column names, not " nor '.
The next error you'll experience will be that you are trying to
module.exports.res = result.rows;
You can't export asynchronous retrieved data like that.
Im making a Node-js app which needs to look up some info from the database before proceeding with another db-call, but I cant seem to make sure that the first check is resolved before proceeding. How can I make sure that the first query is always fulfilled before proceeding? I've tried nesting .next, but they seem to be skipping anyway. So after the first DB-call I want to check the returned value, but its always undefined.
my async function:
async function GetStuff(text, id){
try {
return await db.query(text, id);
} catch(error) {
console.log('fel inne: ' + error)
logger.error('Fel: ' + error)
return null;
}
}
My Controller-code where I call the method and then try await the call with .next.
router.post('/newStuff', async (req, res) => {
//Check if number exist in DB
const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
const values = [req.body.from];
GetStuff(checkUserText, values)
.then(function(result) {
var user = result.rows[0];
//HERE I GET UNDEFINED for some reason. I need to check the result in order to select the next step.
if(user.userid !== null){
console.log(user)
//do some stuff...
}
else {
res.end('Not OK')
}
}).catch(function(error) {
console.log('fel: ' + error)
logger.error('Fel: ' + error)
res.end('Error')
});
})
Instead of returning null from GetStuff, you should probably throw either the original error or a new error. This will then cause GetStuff.catch to be triggered if something goes wrong with the database call.
Just a tip as well, your controller function is async so you don't need to use Promise based structure in your controller code. You can also use async/await.
With both of those, you'd end up with the following code:
async function GetStuff(text, id){
try {
return await db.query(text, id);
} catch(error) {
console.log('fel inne: ' + error)
logger.error('Fel: ' + error)
throw new Error('Failed to get db record');
}
}
router.post('/newStuff', async (req, res) => {
//Check if number exist in DB
const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
const values = [req.body.from];
let dbResult;
try {
dbResult = await GetStuff(checkUserText, values);
} catch (err) {
console.log('fel: ' + error)
logger.error('Fel: ' + error)
res.sendStatus(500);
}
const user = dbResult.rows[0];
if (user.userid !== null) {
console.log(user);
}
// Do some more things...
res.sendStatus(200); // All good!
}
i am pretty new to java script and nodejs.
i am trying to write a code that checks if an email is already exists in the database, and if not send an error.
the problem is that before the database function is ending, my code going to the next line, resulting in undefined variable(emailExists)
this is my code for the sign Up:
app.post('/signUpWeb', function (req, res) {
var reqBody = req.body;
var email= reqBody.email;
var password= reqBody.password;
var fullName= reqBody.fullName;
var webDbInsertion = {email: email, password: password, fullName: fullName};
var emailExists= DButils.checkIfPKexists(connection, "webusersMail", "email", webDbInsertion.email);
if(emailExists == false){
DButils.insertInfoToDB(connection, "webusersMail" ,webDbInsertion);
console.log("successfull signup");
res.send("successfull signup");
}else{
console.log("signup failed, email: " + email + " allready exits");
res.send("signup failed");
}
res.end();
});
and this is for my database call
exports.checkIfPKexists= function(dbConnection, tableName, PK, newPK){
var query = dbConnection.query('select count(*) as mailPkCount from ' +tableName+ ' where ' +PK+ ' = ?', newPK, function (err, row, result) {
if (err) {
console.error(err);
return;
}
var count= row[0].mailPkCount;
var bool = (count > 0);
return bool;
});
};
Well you see, node.JS is designed to be async, while what you're asking isn't impossible, it would shut down the main thread that runs the event loop for that instance of your server.
What I suggest doing is adding a callback function to your "checkIfPKexists" function, and return with the result as a parameter, much like you do in the DBConnection.query. You would then move all the code that isn't getting initialized into your callback.
Edit: Heres a quick code example, polish it up to your liking http://pastebin.com/bEHp4bi2
Background: I have a PHP background and this is my first application using MEAN stack.
I need to save a record but before I must to check if there is any record under the same id already saved in the DB.
In PHP I would do something like this:
Once the user clicks "Save":
1) Call the function to check if an entry with that id already exists
2) If it doesnt, call the save function.
In Javascript, I'm getting a little confused with Promises and so on.
Can somebody give me some light here?
Right now, I'm doing the following:
In the save api, I call this function to check if the record already exists in the DB:
recordExists = findTranscationByBill(billId);
function findTransactionByBill(billId){
results = new promise(function(resolve, reject){
Transactions.find({billId : billId},function(err, transactions){
if(err)
reject("Error: "+err);
//console.log(transactions);
resolve(transactions);
});
});
results.then(function(data){
console.log('Promise fullfilled: '+ data);
}, function(error){
console.log('Promise rejected: ' + error);
});
return $results;
}
The problem is that I think I'm not using promise properly, as my variable doesn't get populated (because its Async).
In the console.log I see that the promise is being fulfilled however, the variable returns as [object Object]
I'm stucked with this problem because I don't know if I should carry on thinking as PHP mindset or if there is a different approach used in Javascript.
Thanks in advance!
In my opinion you could just as well use a callback for this, and since MongoDB has a count method, why not use it
function findTransactionByBill(billId, callback){
Transactions.count({billId : billId}, function(err, count){
if (err) {
callback(err, false);
} else {
callback(null, count !== 0);
}
});
}
and to use it
findTransactionByBill(billId, function(err, exists) {
if (err) {
// handle errors
} else if ( ! exists ) {
// insert into DB
}
}
I think the right function is:
function findTransactionByBill(billId){
var results = new promise(function(resolve, reject){
Transactions.find({billId : billId},function(err, transactions){
if(err) {
reject(err);
} else {
if (transactions.length === 0) {
reject('No any transaction');
} else {
//console.log(transactions);
resolve(transactions);
}
});
});
results.then(function(data){
console.log('Promise fullfilled: '+ data);
}, function(error){
console.log('Promise rejected: ' + error);
});
return results;
}
And then use it like this:
recordExists = findTranscationByBill(billId);
recordExists.then(function() {
// resolved, there are some transactions
}, function() {
// rejected. Error or no any transactions found
// may be you need to check reject result to act differently then no transactions and then error
});
I assume you are using mongodb native drive.
I think mongodb doesn't have promise built-in supported. So you have to promisify it by a little help from promise library. Please refer this if you want to use bluebird.
After promisifying, the code should looks like that (using bluebird):
Promise = require('bluebird');
// Promisify...
var _db = null;
var client = MongoClient.connectAsync('mongodb://localhost:27017/test')
.then(function(db) {
_db = db
return db.collection("myCollection").findOneAsync({ id: 'billId' })
})
.then(function(item) {
if (item)
_db.save(item);
})
.catch (err) {
// error handling
}
The above code is not perfect, because it introduced a global var, so the better version may be
Promise = require('bluebird');
// Promisify...
var client = MongoClient.connectAsync('mongodb://localhost:27017/test')
.then(function(db) {
return Promise.prop({
item: db.collection("myCollection").findOneAsync({ id: 'billId' },
db: db
})
})
.then(function(result) {
var item = result.item;
var db = result.db
if (item)
db.save(item);
})
.catch (err) {
// error handling
}
You need to check bluebird to know how to use it. Also they are many other promise libraries like q, when, but all are similar stuff.
I got a file newuser.js (node.js environment featuring a mongodb database managed via mongoose) containing the following code:
//newuser.js
//basically creates new user documents in the database and takes a GET parameter and an externally generated random code (see randomcode.js)
[...]
var randomCode = require ('randomcode');
var newTempUser = new tempUser({name: req.body.name, vericode: randomCode.randomveriCode(parameter)
});
newTempUser.save(function (err){
//some output
});
//randomcode.js
//creates a random sequence of characters (=vericode), checks if code already exists in DB and restarts function if so or returns generated code
exports.randomveriCode = function randomveriCode(parameter){
[...]
var TempUser = conn.model('TempUser', TempUserSchema);
TempUser.count({vericode: generatedcode}, function(err, counter){
if (counter=='0'){
return generatedcode;
}else{
randomveriCode(parameter);
}
});
};
Problem is, that newuser.js throws an error as variable vericode is 'undefined' (thus mongoose model validations fails). The error does not occur if I skip the database query and instantly return the generated code (which in fact has got a value as verified by several console.log instructions). It occurs to me that the db query takes to long and empty or null value returned before query is complete? I thought about introducing promises unless you got any other suggestions or hints what may cause this behaviour?
Kind regards
Igor
Since querying the database is a non-blocking operation, you cannot expect the function call to return the value from the database immediately. Try passing in a callback instead:
// newuser.js
var randomCode = require('randomcode');
randomCode.randomveriCode(parameter, function(err, code) {
if (err) throw err; // TODO: handle better
var newTempUser = new tempUser({name: req.body.name, vericode: code});
newTempUser.save(function (err){
//some output
});
});
// randomcode.js
exports.randomveriCode = function randomveriCode(parameter, cb) {
var TempUser = conn.model('TempUser', TempUserSchema);
TempUser.count({vericode: generatedcode}, function(err, counter) {
if (err) return cb(err);
if (counter == '0') {
cb(null, generatedcode);
} else {
randomveriCode(parameter, cb);
}
});
};
your randomveriCode function contains calls to an asynchronous function and therefore, your function really needs to provide a callback argument like this:
exports.randomveriCode = function randomveriCode(parameter, callback){
[...]
var TempUser = conn.model('TempUser', TempUserSchema);
TempUser.count({vericode: generatedcode}, function(err, counter){
if(err) return callback(err);
if (counter=='0'){
return callback(null, generatedcode);
}else{
randomveriCode(parameter, callback);
}
});
};
You'd then call it like so:
var randomCode = require ('randomcode');
randomCode(function(err, vericode){
if(err) throw err;
var newTempUser = new tempUser({name: req.body.name, vericode: vericode});
newTempUser.save(function(err,newUser){
//do something here
});
});
Btw - you could also use a synchronous function to create a GUID. See https://www.npmjs.org/package/node-uuid.