getJSON not getting data from database - getjson

function find()
{
var id = $('#Id').val();
$.getJSON("api/questionsanswer/" + id,
function (data)
{
var str = data.Username + ': $ ' + data.Questions;
$('#questionanswer').text(str);
})
.fail (
function (jqXHR, textStatus, err) {
$('#questionanswer').text('Error: ' + err);
});
}
I try to get the data it display "null: null"
so it seems that data.Username and data.Questions wasn't capture... what is wrong with my code??

Related

I have problems with the connection of dialogflow cx and firestore database

can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
Hello, can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
const Firestore = require('#google-cloud/firestore');
const PROJECTID = 'ia-proyecto';
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.db_datos_personales = (req, res) => {
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
console.log('Dialogflow Request body: ' + JSON.stringify(req.body));
let tag = req.body.fulfillmentInfo.tag;
console.log('Tag: ' + tag);
console.log('Session Info Parameters: ' + JSON.stringify(req.body.sessionInfo.parameters));
//
if (tag === 'nombre') {
const COLLECTION_NAME = 'Datos_Personales';
let Nombre_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['nombre_usuario']), '"', '');
let Ciudad_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['ciudad_usuario']), '"', '');
console.log('Nombre usuario: ' + Nombre_Usuario);
console.log('Ciudad usuario: ' + Ciudad_Usuario);
const data = {
Nombre_Usuario: Nombre_Usuario,
Ciudad_Usuario: Ciudad_Usuario,
};
console.log(JSON.stringify(data));
var answer = 'Welcome to the Cloud Audio family, '+ Nombre_Usuario +'! Enjoy our services.';
return firestore.collection(COLLECTION_NAME)
.set(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to store', err });
});
//
} else if (tag === 'pregunta') {
const COLLECTION_NAME = 'Pregunta_Usuario';
let pregunta_usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['pregunta_usuario']), '"', '');
console.log('Pregunta Usuario: ' + pregunta_usuario);
const data = {
pregunta_usuario: pregunta_usuario
};
console.log(JSON.stringify(data));
var answer = 'Your plan has been changed to the '+ pregunta_usuario + ' service.';
return firestore.collection(COLLECTION_NAME)
.doc(phone_number)
.update(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to update field', err });
});
}
};
I hope to have a solution, since I was more than a week and I can't find anything.

Variables defined or changed inside indexedDB event handlers

I’m working on indexedDB and have a problem. The problem is when I request some transaction such as add or read from database. When I handle the event [onsuccess, onerror] and change/assign a value of/to a variable it persist that value and accessible inside that handler but outside the handler the value doesn’t change.
let getValue = {};
function getAll_PROMISE(signedInUser){
return new Promise(function(resolve, reject){
getValue = index.getAll(signedInUser);
getValue.onsuccess = function(event){
if(event.target.result){
alert("event.target. got result " + event.target.result);
resolve(event.target.result);
}else{
alert("Event.target have not result");
reject(undefined);
}
}
getValue.onerror = function(event){
reject(event.target.errorCode);
}
});
}
(function(){
try {
includedDate.forEach(async function(eachDate){
await getAll_PROMISE(currentSignedInUser).then((arrayOfObject) => {
foundNothing = false;
alert("foundNothing... "+foundNothing + arrayOfObject); //foundNothing is false here
arrayOfObject.forEach(function(usernameKey){
if(serializeDate(eachDate) == usernameKey.dateValueSaved){
console.log("foundDate: " + usernameKey.dateValueSaved + "wechi" +usernameKey.wechi + " mahtem: " + usernameKey.mahtem);
}
});
}, (rejectReason) => {
alert("The promise didn't reply anything or it rejected! " + rejectReason);
});
});
}catch(err){
alert("Catching error inside catch block: " + err);
}
})();
the variable foundNothing is not retain its value event after I use Promise!

Mongodb insert error - Must not contain '.'

I am inserting login tokens into my database, but I keep getting 'Error: key services.resume.appLoginToken.date must not contain '.'
My code below is :
if(!result.services.resume || result.services.resume.appLoginToken == null){
var tokenStr = email + Math.random(1,100);
tokenStr = Base64.encode(tokenStr);
queryStr = {
"services.resume.appLoginToken.date": Date(),
"services.resume.appLoginToken.base64Token": tokenStr
};
collectionUser.insert(queryStr, function(err, result) {
if(err)
{
console.log('Error:'+ err);
return;
}
});
}
Any help would be great, thank you

parse.com afterDelete trigger doesn't work completely

I have a Parse class Comment. Each Comment is submitted by a ParseUser and I wanna track in my parse user how many comments he has submitted, so I've created the following triggers in Parse Cloud Code:
/*
* ------------- AFTER SAVE
*/
Parse.Cloud.afterSave("Comment", function(request) {
//if it's the first save
if(!request.object.existed()) {
//increment the User's comments
query = new Parse.Query(Parse.User);
query.get(request.object.get("createdBy").id, {
success: function(user) {
user.increment("comments");
user.save();
}, error: function(error) {
console.log("Error searching the User");
}
});
}
});
/*
* ------------- AFTER DELETE
*/
Parse.Cloud.afterDelete("Comment", function(request) {
//decrement the User's comments
console.log("The user who submitted the comment has the id: " + request.object.get("createdBy").id);
query = new Parse.Query(Parse.User);
query.get(request.object.get("createdBy").id, {
success: function(user) {
console.log("Retrieved the user. He has username: " + user.get("username"));
user.increment("comments", -1);
user.save();
}, error: function(error) {
console.log("Error searching the user - error afterDelete#Comment 2");
}
});
});
The problem is that the afterSave trigger works, but the afterDelete doesn't and I can't figure out why. I can retrieve the User because the two console.log show out which is the correct user, but I can't save it, after the increment(user, -1). Thanks in advance.
EDIT:
Here the User trigger:
/*
* ------------- BEFORE SAVE
*/
Parse.Cloud.beforeSave("User", function(request, response) {
var comments = request.object.get("comments");
if(comments == null || comments < 0)
request.object.set("comments", 0);
var itemSaved = request.object.get("itemSaved");
if(itemSaved == null || itemSaved < 0)
request.object.set("itemSaved", 0);
var username = request.object.get("username");
if(username.length < 6 || username.length > 20)
response.error("username must be longer than 6");
else {
response.success();
}
});
/*
* ------------- AFTER DELETE
*/
Parse.Cloud.afterDelete("User", function(request) {
query = new Parse.Query("Comment");
query.equalTo("createdBy", request.object.id);
query.find({
success: function(comments) {
Parse.Object.destroyAll(comments, {
success: function() {},
error: function(error) {
console.error("Error deleting related comments " + error.code + ": " + error.message);
}
});
},
error: function(error) {
console.error("Error finding related comments " + error.code + ": " + error.message);
}
});
});
Per Parse's documentation, "If you want to use afterDelete for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself."

How do I send a Mongo Document back to the front end?

//router
app.get('/retrieve_report', function(req, res) {
var retrieved = retrieve_report(req, res);
res.render('retrieve_report.ejs', {
'report' : retrieved
});
});
//Load up the report model
var Report = require('../models/report');
console.log('Report ' + Report.schema);
//expose this function to our app using module.exports
//query
module.exports = function(req, res) {
//console.log('param ' + res.send);
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
}
//app.js
var retrieve_report = require('./config/retrieve_report');//which is the above code
I want to return the document to the router so that I can put its information into my view. I tried "res.json(doc), but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');" Everyone says to use a callback function, but aren't I using a callback function here?
As your error says:
but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');"
Means you are trying to send data the twice.
Sample code:
app.get('/retrieve_report', function(req, res) {
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
This should work..