nodejs inherit function inside a function - node.js

im trying to inherit a function inside one, but im not sure how.
function register(Username, Password, callback)
{
var result;
UserModel.findOne({username: Username}, function(error, data)
{
if(error)
console.log(error);
if(data)
result = 'already exist';
mongoose.connection.close();
if(!data)
{
var user = new UseModel(
{
username: Username,
password: Password
});
user.save(function(error)
{
if(error)
{
console.log(error);
result = 'Error';
}
result = 'success';
mongoose.connection.close();
});
}
});
callback;
}
i thought that making a callback, i would be able to set a custom function in there.
i've seen someplaces that people do inherit functions inside another one, but i dont find them anymore and im trying to do them, for this code im saving a record in mongo.
so lets just say, in the other code, im calling this function with first 2 parameters, and the third would do the function i want it to do depending of the result, just like this.
this.register('myname', 'mypassword', function(
{
if(result != 'error')
{
response.render('register',
{
'Title': Title,
'result': result
});
}
}));
im not sure if the inherit is like this. but this is what im trying to do, im learning js with node so please sorry about my unexperience.
PD: im using express, swig, body-parser and mongoose modules for node.js

Here's how your register() function might look:
function register(Username, Password, callback)
{
UserModel.findOne({username: Username}, function(error, data)
{
if(error)
return callback(error);
if(data)
return callback(null, 'User already exists');
var user = new UseModel(
{
username: Username,
password: Password
});
user.save(function(error)
{
if(error)
return callback(error);
callback(null, 'Success');
});
});
}
Here's how it would be used:
this.register('myname', 'mypassword', function(error, result)
{
if (error)
return console.error(error); // do something better here
response.render('register',
{
'Title': Title,
'result': result
});
});

Related

MongoDb findOne query results in error - even if data is found

the below is my controller function
exports.validateUsername = async (uName) => {
console.log("inside validate username");
await User.findOne({ username: "sab2" }).then(function (err, user) {
if (err) {
console.log("inside err");
console.log("error");
console.log(err);
return true;
} else {
console.log("inside user found");
console.log("user");
console.log(user);
return false;
}
});
};
I have record in my "user" collection with username ="sab2". But still , the promise function results in err, and goes inside if(err).
But when I do console.log(err) I get the actual user data "sab2" object.
I have a doubt if the function syntax is function(data,err).
Error object printed
Please suggest a solution.
The then() on a findOne does not return a error, I would rewrite like this:
User.findOne({ username: "sab2" }, function(err, user) {
if (err) {
console.log("inside err");
console.log("error");
console.log(err);
return true;
} else {
console.log("inside user found");
console.log("user");
console.log(user);
return false;
}
});
then do not return error. Do something like this to catch error
await User.findOne({ username: "sab2" }).then((user) => {
console.log(user)
}).catch(error=>console.log(error))
or use callback. See here

Using node.js 'util' to promisify is returning an error

I'm trying to create a function in a file to return a promis, which I will call form another file. I'm trying to use the 'util.promisify' to wrap the function, but I'm getting an error. Here is the code and the error:
from my 'checkEmail.js':
const Profile = require('../../models/profile');
const util = require('util');
var exports = module.exports = {};
exports.findEmail = util.promisify(checkEmail());
function checkEmail (email) {
Profile.findOne({ 'emails': { $elemMatch: { email_address: email } } }, (err, userEmail) => {
let conclusion = false;
if (err) {
console.log('Error in looking up an existing email');
} else {
if (userEmail) {
console.log('We found an existing owner for email: ' + email);
conclusion = true;
}
}
return conclusion;
})
}
Calling it on 'profile.js':
router.route('/addemail/:id')
// ADD EMAILS
.put(function (req, res) {
Profile.findOne({ 'owner_id': req.params.id }, function (err, profile) {
if (err)
res.send(err);
EmailCheck.findEmail(req.body.email_address).then((data)=>{
console.log('The answer is: ', data);
});
profile.emails.push({
email_type: req.body.email_type,
email_address: req.body.email_address
})
profile.save(function (err) {
if (err)
res.send(err);
res.json(profile);
});
});
});
The error I'm getting is:
Config for: http://localhost:3000
internal/util.js:272
throw new ERR_INVALID_ARG_TYPE('original', 'Function', original);
Any help would be appreciated.
In order to promisify the function that you pass to util.promisify must:
Take a function following the common error-first callback style, i.e.
taking a (err, value) => callback as the last argument, and returns a version that returns promise
So you can either promisify Profile.findOne, or pass a callback as the last argument to checkEmail
function checkEmail (email, callback) {
Profile.findOne({ 'emails': { $elemMatch: { email_address: email } } }, (err, userEmail) => {
let conclusion = false;
if (err)
return callback(new Error('Error in looking up an existing email'));
if (userEmail) {
console.log('We found an existing owner for email: ' + email);
conclusion = true;
}
return callback(null, conclusion);
})
}
And then you should call it like this:
exports.findEmail = util.promisify(checkEmail);
Otherwise you're passing to .promisify the returned value of checkEmail which is not a function following the style commented above.
You have typo, use util.promisify(checkEmail) instead, parentheses are redundant

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

Is it good practise to use async in nodejs ? How to use helper function in nodejs?

I am new to nodejs and I want to create helper function for finding user from collection. I want to excute that helper function before adding any new document into the database. Parallaly I want to use that helper function on multiple times in other places.
When I simply create one function and store result of that function, the control is passes from that place and doesn't wait for output as Nodejs basic Async functionality.
How can I customise my code to use helper function and wait for the result and then perform required operation
How to use nested callback ?
Nested callback isn't waiting for callback data and control goes to next line
Here is my code :
login: function (req, res) {
var user = helpers.checkIfDataExists(req.body.mobileNumber, function (user) {
if (user) {
console.log('user exists');
var email = helpers.checkIfDataExists(req.body.email, function (email) {
if (email) {
console.log('email exists');
} else {
console.log('email not exists');
}
});
} else {
console.log('user not exists')
}
});
}
I want that control waits till function is executed and then condition will get executed.
Here control goes by default in else part everytime.
Here is code of helper function :
checkIfDataExists: function (value, callback) {
User.find({mobileNumber: value})
.exec(function (err, result) {
if (err) {
console.log('Error occured');
callback(false);
} else {
console.log('result found');
callback(result);
}
});
},
Use callbacks. Pass a callback function to your helper function in which the results will be returned and then in your helper function write a call to that function when your computations are over.
checkIfDataExists: function (value, callback) {
User.find({mobileNumber: value})
.exec(function (err, result) {
if (err) {
console.log('Error occured');
callback(false);
} else if (!result) {
console.log('Not Found');
callback(false);
} else {
console.log('result found');
callback(result);
}
});
},
then use something like this in your main function.
signUp: function (req, res) {
var user = helpers.checkIfDataExists(req.body.mobileNumber, function(user){
// do something with results here
log(user);
if (!user) {
// add new user
} else {
res.send("User exists");
}
});
}
here is a link to article about callbacks

how to use Promise with express in node.js?

I am using Promise with Express.
router.post('/Registration', function(req, res) {
var Promise = require('promise');
var errorsArr = [];
function username() {
console.log("1");
return new Promise(function(resolve, reject) {
User.findOne({ username: req.body.username }, function(err, user) {
if(err) {
reject(err)
} else {
console.log("2");
errorsArr.push({ msg: "Username already been taken." });
resolve(errorsArr);
}
});
});
}
var username = username();
console.log(errorsArr);
});
When I log errorsArray, it is empty and I don't know why. I am new in node.js. Thanks in advance.
Try the following, and after please read the following document https://www.promisejs.org/ to understand how the promises work.
var Promise = require('promise');
router.post('/Registration',function(req,res,next) {
function username() {
console.log("agyaaa");
return new Promise(function(resolve,reject) {
User.findOne({"username":req.body.username}, function(err,user) {
if (err) {
reject(err)
} else {
console.log("yaha b agyaaa");
var errorsArr = [];
errorsArr.push({"msg":"Username already been taken."});
resolve(errorsArr);
}
});
});
}
username().then(function(data) {
console.log(data);
next();
});
});
You can have other errors also (or things that shouldn't be done that way). I'm only showing you the basic use of a Promise.
router.post('/Registration', function(req, res) {
return User
.findOne({ username: req.body.username })
.then((user) => {
if (user) {
return console.log({ msg:"Username already been taken" });
}
return console.log({ msg: "Username available." });
})
.catch((err)=>{
return console.error(err);
});
});
you can write a clean code like this.
Promise is a global variable available you don't need to require it.

Resources