I'm using parse open source. I have three tables:
1. ForumPost
2. ForumReply
3. ForumComment
When a user creates a post it will store into ForumPost, when someone adds a reply to the post we are storing post reply on ForumReply table. Now any user can comment on Forum Reply we are storing comments into ForumComment.
What I want: I have an post id, Now I want to get all reply of that post along with their respective comments.
What I have done I am able to get Post Reply but not able to get their comments in the same query. I am calling a Cloud function for every post reply to get comments.
Here is my current code
isRequestLegitimate(request).then(function(result) {
if (result.legitimateRequest) {
var forumQuery = new Parse.Query("ForumPost");
var userPointer = new Parse.User();
userPointer.id = result.activeUserId;
forumQuery.equalTo("objectId", request.params.postId);
forumQuery.include("offer");
forumQuery.include("offer.artist");
forumQuery.include("creator");
forumQuery.include("replies");
forumQuery.include("replies.comments");
forumQuery.include("replies.creator");
forumQuery.select("objectId","offer", "offer.isActive","offer.stopDate", "offer.objectId", "offer.artist.firstname", "offer.artist.lastname",
"offer.title", "offer.picHash", "title", "text", "offer.offer", "creator", "creator.firstname",
"creator.lastname", "replies", "replies.objectId", "replies.text", "replies.creator.firstname", "replies.creator.lastname",
"replies.isRead", "replies.comments.isRead");
forumQuery.first({
useMasterKey: true
}).then(function(forumPost) {
if (forumPost == null) {
response.success("0"); //not found
} else {
response.success(forumPost);
}
}, function(error) {
response.error(error);
});
} else {
response.error("You must be logged in!");
}
});
});```
Could someone please let me know how I can fetch comments?
Related
I'm not sure I'm even attempting the right thing. Heres my issue.
I'm loading data to a screen if the user is authenticated. Its a summary screen. I can click a item and it will send me to a new "details" page (window.location) . I'm passing the ID in the URL and then doing a GET request to get the details to display. When I implement my rules on the firebase DB, (".read": "auth != null"), I get a "401 Unauthorized" error in the console.
So somehow I need to either pass the user to the details.js or set Persistence somehow. Anyone have any suggestions?
THIS IS THE CODE FROM THE MAIN.JS
auth.onAuthStateChanged(user => {
console.log(user);
if (user) {
database.on('value', function(data) {
myData = data.val()
keys = Object.keys(myData)
buildProperties();
})
// tempBuild()
} else {
$('.eachProperty').empty()
$('.eachProperty').append($(`<h1>You must be signed in to view properties</h1>`))
}
})
$('body').on('click', '.singleProp', function() {
id = $(this).attr('id')
window.location = "/details.html?id=" + id
})
THIS IS THE CODE FROM THE DETAILS.JS
var myLocation = location.search.slice(4)
$.get(`https://XXXXXX.firebaseio.com/property/${myLocation}/.json`).then(myProperty)
function myProperty(prop) {
$('.propAddress').text(prop.address)
$('.zip').text(prop.zip)
if(prop.pictures){
for (var i = 0; i < prop.pictures.length; i++) {
var myImg = prop.pictures[i]
$('.imgContainer').append($(`<div class="eachPicDiv"><img src="${myImg}" alt="0" class="detailPic">
<ion-icon class="rBtn" name="arrow-redo-outline"></ion-icon>
</div`))
}
} else {
$('.imgContainer').append($(`<h1>THERE WERE NO PICTURES</h1>`))
}
}
You are using jQuery to fetch your data from Firebase Database,
$.get is a jQuery method, and for that to succeed you need to have some sort of auth token.
Firebase already provides best in class access, read more about access here.
Learn by example here.
I have three database i.e, main_db it is default load database. I want load database after login.
Database are:-
main_db
->user_collection
psm_2017_db
->abc_collection
->xyz_collection
psm_2018_db
->abc_collection
->xyz_collection
Here is my project structure
here is my login script.
client
|->login
|->login.js
Template.login.rendered = function(){
SessionStore.set("login_user",false);
};
Template.login.events({
'submit #formLogin': function (event, target){
event.preventDefault();
var email = target.find('#loginEmail').value;
var password = target.find('#loginPassword').value;
// console.log(email +" "+password);
Meteor.loginWithPassword(email, password, function(err){
if(err){
console.log(err);
alert("Invalid Login!");
}
else {
SessionStore.set("login_user",true);
console.log('successfully')
Router.go("/dashboard")
}
});
}
});
Template.layout.helpers({
"isLoggedin": function () {
return SessionStore.get("login_user");
}
});
here is my load collection file
lib
|->collection.js
abcCollection=new Mongo.Collection("abc_collection");
xyzCollection=new Mongo.Collection("xyz_collection");
You can connect to multiple dbs using the below approach.
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
<<mongo_url>> is your standard mongodb url.
Eg. mongodb://127.0.0.1:27017/database_name
Now, in your specific scenario, main_db contains the user collection (I'm under the assumption that this is pertaining to meteor user collection). You need to have this loaded at all times. You can't have it load after login since user information - which is required for logging in resides in that db!
Once you take care of the above, connecting to the remaining two dbs can be done on login as below:
/lib/dbconnection.js (this will be common to both server and clinet)
Meteor.methods({
loadDB: function(){
if(Meteor.userId()){ // if a user has logged in
var database = new MongoInternals.RemoteCollectionDriver("<<mongo url>>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
}
}
})
Meteor.call("loadDB");
loadDB will get called each time a user logs in. But I fear that it will be run each time any user logs in. In order to avoid it being re-initialized for each user login, you might want to do a check on whether database or myCollection already exists.
It's about time I call in the big guns for this as I can't seem to figure it out.
I have a simple CRUD API in Node. I'm using EJS on the front-end. Essentially, I've got a selectAllRecords view where I display a table of all the records. I have a button next to each record to edit the record. When the button is clicked, it redirects to an editrecord.ejs page, hits the API for a single record where each line is displayed as a value in an input box. From there, I have an onclick method with an XMLHttpRequest making a put request to update the database. However, I'm getting an error - 500 (Internal Server Error) - I'm sure it's something fairly simple I'm missing, but I can't seem to figure it out.
Any help is greatly appreciated! Code below:
First on my view:
<script type="text/javascript">
function someFunc() {
var id = <%= id %>;
var url = '/api/edit/' + candID;
console.log('url ' + url);
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var data = {
name: name,
email: email,
}
var json = JSON.stringify(data);
console.log('json ' + json);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
};
and in my queries.js file:
function updateCandidate(req, res, next) {
var candID = parseInt(req.params.id);
console.log('hit update');
console.log('name ' + req.body.name);
db.none('update cands set name=$1, email=$2 where id=$3',
[req.body.name, req.body.email, candID])
.then(function () {
var candID = candID
var name = data.name;
var email = data.email;
res.render("edited", {"candID":candID, "name":name, "email":email});
})
.catch(function (err) {
return next(err);
});
}
A potentially important note, when I hit the update button and execute the someFunc() function, the dev tool logs show a PUT request to 'api/edit/50' (or whatever ID) and '500 (Internal Server Error)' -- If i hard reload the 'getAllRecords' view, the updates are reflected so it's an issue with the render or redirect (I've tried both)
EDIT
As suggested, I removed the render from the updateCandidate method, but I still get a 500 Internal Server Error. the devtools show me the PUT request is hitting the right URL so i'm really not sure why this isn't functioning correctly. Updated code below...
function updateCandidate(req, res, next) {
var candID = parseInt(req.params.id);
db.none('update cands set name=$1, email=$2, client=$3, jobtitle=$4, question1=$5, question2=$6, question3=$7 where id=$8',
[req.body.name, req.body.email, req.body.client,
req.body.jobtitle, req.body.question1, req.body.question2, req.body.question3, candID])
.then(function (data, err) {
res.status(200)
.json({
status: 'success',
message: `Edited Candidate`
});
})
.catch(function (err) {
return next(err);
});
}
You are sending an ajax request to update the record. So, you should not try to render a view or redirect user as the response of this request. Instead, you can send back a JSON object with some properties e.g. "status".
Then on client side, you check the returned JSON response and based on "status" parameter ( or any other you chose ), you can either update your data or reload the page using window.reload on client side.
Your db query says
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email]) ...
Shouldn't it be
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email, candID])
A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.
I am creating a mobile application for windows phone 8, iOs android. I'm using windows azure for holding some profile application and some device information. I have very little experience with JavaScript although after banging my head against a brick wall all day its starting to click i think. This being said you'll probably laugh at my code below.
This (below) is the insert statement for a table called Devices.
im trying to do a normal insert if there isn't currently any record for the userId.
If there is already a record then update that record instead.
function insert(item, user, request) {
item.userId = user.userId;
var deviceTable = tables.getTable('Devices');
deviceTable
.where({
userId: user.userId
}).read({
success: function(results) {
if (results.length > 0) {
// Device record was found. Continue normal execution.
deviceTable.where({
userID : user.userId}).update({
//i put this here just because i thought there had to be a response
success: request.respond(statusCodes.OK, 'Text length must be under 10')
}) ;
console.log('updated position ok');
} else {
request.execute();
console.log('Added New Entry',user.userId);
//request.respond(statusCodes.FORBIDDEN, 'You do not have permission to submit orders.');
}
}
});
}
I think you'll want something like this:
function insert(item, user, request) {
item.userId = user.userId;
var deviceTable = tables.getTable('Devices');
deviceTable
.where({
userId: user.userId
}).read({
success: function(results) {
if (results.length > 0) {
//We found a record, update some values in it
results[0].fieldName = X;
//Update it in the DB
deviceTable.update(results[0]);
//Respond to the client
request.respond(200, results[0]);
console.log('updated position ok');
} else {
//Perform the insert in the DB
request.execute();
console.log('Added New Entry',user.userId);
//Reply with 201 (created) and the updated item
request.respond(201, item);
}
}
});
}