i'm trying to check if user already exite before register but not work for me
when i test in postman it's still created user any idea ?
create: function (req, res) {
if (req.body.password !== req.body.confirmPassword) {
return res.json(401, {err: 'Password doesn\'t match, What a shame!'});
}
User.find(req.body).exec(function(err,users){
if (err) {
return res.negotiate(err);
}
if (users.length) {
res.status(400);
return res.json('User already exists!');
}
}else{
User.create(req.body).exec(function (err, user) {
if (err) {
return res.json(err.status, {err: err});
}
// If user created successfuly we return user and token as response
if (user) {
// NOTE: payload is { id: user.id}
res.json(200, {user: user, token: jwToken.issue({id: user.id})});
}
});
}
});
try edit your code in this lines
User.find(req.body).exec(function(err,users){});
to :-
User.findOne({email:params.email}).exec(function(err,user){
if(user){
/**
*user exists !
*/
}else{
/**
*create new user
*/
}
}
because you use find with criteria which isn't exist so it's returns
null and create new user in every time
If you want to have users with unique username and/or email you can use unique type in model's attribute definition like this:
attributes: {
username: {
type: 'string',
unique: true
}
}
Then your controller method would look like this:
create: function (req, res) {
if (req.body.password !== req.body.confirmPassword) {
return res.json(401, {err: 'Password doesn\'t match, What a shame!'});
}
User.create(req.body, function (err, user) {
if (err) {
return res.negotiate(err); // validation error will be automatically passed there
}
res.json(200, {user: user, token: jwToken.issue({id: user.id})});
});
});
Related
Inside the database, I manually verified there exists a user with username R0H1 but when I use the below code it just sends back "No such user".
The same problem occours with username Harshitsin75, whereas it correctly finds all other alphanumeric usernames for example akhil, test123 etc. And this problem occours everytime I try to open the profile for the users R0H1 and Harshitsin75.
app.get("/profile/:userName", function(req, res) {
if (req.isAuthenticated()) {
User.findOne({username: req.params.userName}, function(err, foundUser) {
if (err) console.log(err);
else {
if (foundUser) res.render('User-profile', {user: foundUser});
else res.send("No such user");
}
});
} else {
res.redirect('/login');
}
});
Try this:
Users.find({ username: { $regex: req.query.username }, })
I know how to read from the google finance api, it is pretty simple.
But when I try to write I get the following error:
Error: Request had insufficient authentication scopes
This is my code:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('./GoogleFinanceApi/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), appendData);
});
Here ^ in the append data is where I am calling the function, it works when i do the listMajors but not when I do the appendData...
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}
function appendData(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.append({
auth: auth,
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}
What am I doing wrong? I have read some posts and they say they didn't add the resource so I tried to fix that but still nothing works...
Probably the issue is in google.sheets in appendData. Perhaps you need to pass auth to google.sheets before you access sheets as how you are doing in listMajors but you are passing auth to the sheets instead of google.sheets. This might be an issue
Can you try below updated code
function appendData(auth) {
const sheets = google.sheets({version: 'v4', auth})
sheets.spreadsheets.values.append({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}
the function runs and console.log shows the user object on the backend. I don't understand why it's telling me there is an issue here, and really need some guidance.
vm.register = function() {
//check that passwords match
if(vm.password != vm.passwordRepeat) {
vm.registerError = "Passwords must match.";
return;
} else {
var username = vm.username;
// console.log("Valid form. Checking for existing user",username);
storeDataFactory.userExists(username).then(function(response){
//if user exists, return error
if(response.data.length > 0) {
vm.registerError = "A user with email " + username + " already exists. Please login.";
return;
} else {
//if no user exists
if(response.data.length == 0) {
// console.log("No user exists. Continue with registration.");
}
//assign info to user object
var user = {
username: vm.username,
password: vm.password,
name: vm.name,
phone: vm.phone
};
**storeDataFactory.createUser(user).then(function(response){**
vm.user = response.data;
console.log("Created user", vm.user);
if(response.data.length > 0) {
console.log("Created user", vm.user);
vm.registerMessage = "Successful registration, please login";
vm.registerError = null;
vm.user = response.data;
}
}).catch(function(error){
console.log(error);
vm.registerError = "There was an error creating your account.";
vm.registerMessage = null;
});
}
});
}
};
The backend code:
module.exports.register = function(req, res) {
console.log('registering user', req.body);
//create the user object with hashed pass
User
.create({
username: req.body.username,
name: req.body.name,
phone: req.body.phone,
password: bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10))
}, function(err, user) {
if (err) {
console.log("Error creating account");
res
.status(400)
.json(err);
} else {
console.log("Account created!", user);
res
.status(201)
.json(user);
}
});
};
Account created! and the user object are logged on the backend. It just won't display that damn Successful Registration! Please login. message.
storeDataFactory code:
/* global angular */ angular.module('rumbleApp').factory('storeDataFactory', storeDataFactory);
function storeDataFactory($http) {
return {
userExists: userExists,
createUser: createUser
};
function userExists(username) {
return $http.get('/api/users/userExists/' + username).then(complete).catch(failed);
}
function createUser(user) {
$http.post('/api/users/register', user).then(complete).catch(failed);
}
function complete(response) {
return response;
}
function failed(error) {
console.log(error.statusText);
return "There was an error with the API call.";
}
}
Are you sure you're returning from storeDataFactory.createUser()? Can you post the code for that method?
Sounds like the code is executing, but you're not returning anything from it (hence why it thinks it's undefined)
I am new in nodejs and I want to make a json array by comparing id inside a loop but the MongoDB function does not wait for the loop to complete, so data is not coming out properly. It displays the data before the loop ends, below is the code:
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else{
async.waterfall([
function (done) {
var countryalldata = [];
for (var i = 0; i < cData.length; i++) {
var country_s = cData[i];
State.where('s_c_id').equals(country_s._id)
.exec(function(err, statedata){
country_s.statecount = statedata.length;
//console.log(country_s._id);
console.log(country_s.statecount);
});
countryalldata.push(country_s);
}
done(err, countryalldata);
// console.log(countryalldata);
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({
'status': 1,
'message': 'Data found',
'data': countryalldata
});
}
]);
}
});
});
Here is output of the countryalldata variable printed before the loop will complete. I want to print its output after loop execution is complete.
State.where is asynchronous so it should be synchronized. For example with async.map
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else {
async.waterfall([
function (done) {
async.map(cData, function (country_s, done2) {
// Convert country_s into plain object. It's not a mongoose
// model anymore
country_s = country_s.toObject();
State.where('s_c_id')
.equals(country_s._id)
.exec(function(err,statedata){
if (err) {
done2(err);
return;
}
country_s.statecount = statedata.length;
console.log(country_s.statecount);
done2(null, country_s)
});
}, function(err, countryalldata) {
if (err) {
done(err);
}
else {
done(null, countryalldata)
}
});
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({'status':1,'message': 'Data found','data':countryalldata});
}
]);
}
});
});
Im creating a comments system and im trying to add values to the view such as the text, userName, timePosted and userProfileImageURL but the only one that wont appear is the userProfileImageURL.
I think the problem is with the controller function but it could be somewhere else altogether.
/**
* Comment middleware
*/
exports.commentByID = function (req, res, next, id) {
Comment.findById(id).populate('user', 'displayName').exec(function (err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load Comment ' + id));
req.comment = comment;
next();
});
};
or Here Possibly
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user', 'displayName')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
What does the 'user' and 'displayName' parameter in this function do?
Can i add the 'userProfileImageURL' also to the returned data somehow?
Im using the profileImageURL value like this. display name is showing but not the profileImageURL
<img ng-src="{{post.user.profileImageURL}}" alt="{{post.user.displayName}}" />
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
Just have to delete the displayName parameter and it will send the whole user object.