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.
Related
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");
}
});
}
I have an emails object that contains an array in a mongodb database. However, when I try to use $set to make the array empty it doesn't work. How am I supposed to clear the array?
exports.clearEmails = function(req, res, next) {
var listId = req.params.id;
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
EmailList.update({'_id': listId}, {$set: {'emails': []}}, function(err,results) {
if (err) {
return res.status(400).send(err);
} else {
return res.status(200).send(results);
}
});
}
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})});
});
});
I have code, basically still the MEANJS boilerplate, and I added a section to the articles for commenting. My strategy for the comments was to expose a route in express, /comments/:commentId, with a very simple comment model (it has a user object, a content string, and a likes number). I extended the article model to include an array of object IDs for the comments, and when an article was loaded, my angular resources would make a call to the /comments/:commentId to retrieve the list of comments specified by the array. Following is my server code
/* below is comments.server.controller.js */
/* THIS IS NEVER GETTING CALLED */
exports.updateArticleComments = function(req, res){
Article.findById(req.comment.article).populate('user', 'displayName').exec(function(err, article){
console.log(article);
if (err) return res.json(err);
if (!article) res.json({err: 'oops!'}); //handle this ish
article.comments[article.comments.length] = req.comment._id;
article.save(function(err, article){
if (err){
console.log('error');
} else {
res.json(article);
}
});
});
};
exports.commentsByID = 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();
});
};
/* end comments.server.controller.js */
/* begin articles.server.routes.js */
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
articles = require('../../app/controllers/articles.server.controller'),
comments = require('../../app/controllers/comments.server.controller');
module.exports = function(app) {
// Article Routes
app.route('/articles')
.get(articles.list)
.post(users.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.read)
.put(users.requiresLogin, articles.hasAuthorization, articles.update)
.post(comments.createComment, comments.updateArticleComments)
.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
};
/* end articles.server.routes.js */
Everything, and I mean everything, works, EXCEPT exports.updateArticleComments function. I have seriously written about 5 different function, trying lodash's _extend, and many other techniques. I can't figure out why the comments array is never being filled. Does anyone have any suggestions at all?
EDIT: was requested to share createComment, so here it is
exports.createComment = function(req, res, next){
var comment = new Comment({content: req.body.content, article: req.body.articleId});
comment.user = req.user;
comment.save(function(comment, err){
if (err){
return res.jsonp(err);
} else {
req.comment = comment;
next();
}
});
};
Article.update({_id: 'VAL' }, {
$push: {
'comments' : req.comment._id }},{upsert:true},
function(err, data) { });
Have you tried the push method? I'd also be curious if the value of comment _id is coming back and not undefined.
I want to return a boolean value from middleware defined as
module.exports = {
authenticatepracticename: function(pname) {
ecollection.find({ $and: [{'name':pname},{'status' : 'active'}] }).exec(function (err, result) {
if (err) return false;
if(result.length == 1){
// console.log('true');
return true;
}
else{
// console.log('false');
return false;
}
});
},
// ...
}
to my express controller defined as
exports.checkcredentails = function (req, res) {
var result = practice.authenticatepracticename(practiceName);
}
but result is coming undefined even though middleware function is getting called.
The reason why you are getting undefined result from practice.authenticatepracticename is because ecollection.find performs asynchronous action and authenticatepracticename end without returning any value (which is undefined in JavaScript).
In order to improve that, you would need to provide a callback function from your checkcredentails to authenticatepracticename.
Example:
exports.checkcredentails = function (req, res) {
practice.authenticatepracticename(practiceName, function(err, result){
// you can handle error and result here e.g. by sending them back to a customer
res.send("Result: " + result);
});
}
And your authenticatepracticename:
authenticatepracticename: function(pname, cb) {
ecollection.find({ $and: [{'name':pname},{'status' : 'active'}] }).exec(function (err, result) {
if (err) return cb(err)
if(result.length == 1){
// console.log('true');
cb(null, true)
}
else {
// console.log('false');
cb(null, false)
}
});
}
I hope that will help.