How to get object field in Parse - javascript

Here is my query for a particular User:
var query = new Parse.Query("User");
query.get(userId, {
success: function(user) {
if (user === undefined){
response.success("No such user with this ID: " + userId)
}else{
response.success("successfull " + user.get('authData')); // authData is undefined whereas name, minAge and other primitive types are working fine
}
},
error: function() {
response.error("user lookup failed");
}
});
That user.get('authData') is returning undefined, however other primitive type fields such as name and age are working fine.
I am thinking it is because authData is object
How can I access it?

Related

API Call is going after providing conditions in JavaScript

I am trying to make API call and sending storeId and consultuntId to backend, its working fine.
This is the code:-
const urlParams = new URL(window.location.href).searchParams;
const live_shopping_events_parameter = Object.fromEntries(urlParams);
$.ajax({
type:'POST',
url: '/aos/lscommission',
data: {
storeId: live_shopping_events_parameter.r,
consultuntId: live_shopping_events_parameter.z,
},
success: function (){
},
error: function(error) {
},
});
But I need to check two condition
the url fields exist and are valid
non-empty numeric for storeId and consultantId
This is the Example URL - https://www.example.com/live-shopping-events?r=MDQyMDE%3d&z=56
Where r is is the storeId and z is the consultuntId.
This is my code to check non-empty numeric for storeId and consultantId
const urlParams = new URL(window.location.href).searchParams;
const live_shopping_events_parameter = Object.fromEntries(urlParams);
if(live_shopping_events_parameter !== 'undefined' || live_shopping_events_parameter !== null ) {
$.ajax({
type:'POST',
url: '/aos/lscommission',
data: {
storeId: live_shopping_events_parameter.r,
consultuntId: live_shopping_events_parameter.z,
},
success: function (){
},
error: function(error) {
},
});
}else{
console.log("error");
}
for this code if I remove parameters (https://www.example.com/live-shopping-events), then still it is making API call.
How to solve this issue.
You are trying to condition in the whole object returning from Object.entries which will always return an object. That is why your condition is becoming true always. You should try to factor in the property you are trying to find, like this:
if (live_shopping_events_parameter.r !== undefined || live_shopping_events_parameter.z !== undefined) {
/* You code here */
}
SOULTION EXPLAINATION:
Thats because irrespective if there are url params or not the Object.fromEntries(urlParams) will return an object. If you want to check if params exist you need to check individually like live_shopping_events_parameter.r, this will return true is param exists and false if param is absent and make API call only when it is true.
SOULTION CODE:
const urlParams = new URL(window.location.href).searchParams;
const live_shopping_events_parameter = Object.fromEntries(urlParams);
if(live_shopping_events_parameter.r && live_shopping_events_parameter.z) {
//Params exist
//Make API call here..
console.log('Calling API')
}else{
// No params found
console.log('Params missing')
}

How to not pass the value by function when using mongoose

There is an api as below.
try catch is omitted here.
exports.test = async(req,res) => {
const {clientId} = req.body;
// There is a function that makes an object to use repeatedly.
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
clientId,
reason: arg1,
});
return errorLogs;
}
errorReason("server error").save();
And this is the type of clientId.
clientId: mongoose.Schema.Types.ObjectId
When I can pass obejctId or empty String for clientId as request.body.
But when I send empty string, it occurs an error.
validation failed: clientId: Cast to ObjectID failed for value \"\"
at path \"clientId\"
How can I make correct function of errorReason? I don't want to save "null" or "empty string" for clientId, even though clientId is empty string.
I hope there isn't clientId for 'new ErrorLogs', when clientId is empty string.
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
reason: arg1,
});
return errorLogs;
}
Thank you so much for reading it.
You can achieve this by making the required field in your schema consume a function. This function decides whether the field is required depending on the type. This will allow you to save an empty string.
If you want to save an empty string:
to save an empty string:
const mongoose = require('mongoose');
const errorSchema = new mongoose.Schema({
clientId: {
type: mongoose.Schema.Types.ObjectId,
required: function(){
return typeof this.clientId === 'string' ? false : true
},
}
});
const Errors = mongoose.model('errors', errorSchema)
Update: Seems I misunderstood your intention. If you just want to not set the field clientId in the document, pass undefined to the Schema when you have an empty string. Mongoose will not save the field (unless you have it required, in which case mongoose will throw an error)
exclude empty string field from saved document:
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
clientId: clientId || undefined, // handles '', undefined, null, NaN etc
reason: arg1,
});
return errorLogs;
}
errorReason("server error").save();
You should use code like bellow.
exports.test = async(req,res) => {
const {clientId} = req.body;
// There is a function that makes an object to use repeatedly.
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
clientId : clientId, // add here clientId for asign clientId to field
reason: arg1,
});
return errorLogs;
}
if(!!clientId){ //Here !! means not equal to blank,null,undefine and 0
errorReason("server error").save();
}

Mongoose: updating new values only if not null

I already got another solution but cannot understand why mine doesn't work.
I tried to use $set: here but it didn't help. objForUpdate do return "name, lastname" when i print. If i replace {objForUpdate} with {name, lastname} - update works. But I cannot pass the parameters in variable.
//Route to UPDATE user
async updateUser(req, res) {
let { _id, type, name, lastname } = req.body;
try {
let objForUpdate = "";
for (var key in req.body) {
if (req.body.hasOwnProperty(key) && req.body.key !== null && req.body[key] !== "" && key !== '_id') {
console.log("this is key: " + key + ", and this is value req.body[key]: " + req.body[key]);
objForUpdate += key + ", ";
}
}
objForUpdate = objForUpdate.slice(0, -2);
const updated = await Users.updateOne({ _id }, {objForUpdate});
res.send({ updated });
} catch (error) {
res.send({ error });
}
}
If you would debug the code, you'll get it.
Lets say the req.body looks like { name: "foo", lastname: "bar" type: "2", _id: 1} and by the end of the for-loop and the slice op the objForUpdate would be "name, lastname, type" which is a string.
Now when you pass this string to the updateOne op, this part {objForUpdate} will get converted to { objForUpdate: "name, lastname, type" } (a conversion of identifier as key and its defined value as the value of that key).
And that update object is incorrect even with $set operator.
If i replace {objForUpdate} with {name, lastname} - update works. Why?
Because in this case with Object destructuring you unpacked the object as independent variables (name, lastname ...) with values. In this case the {objForUpdate} when passed would become {"name":"foo", "lastname":"bar", "type":"2"} which is correct as update object.

Why isn't my collection.upsert() query NOT setting multiple parameters to the collection?

I have an collection.upsert() function in my Meteor method. For some strange reason it only seems to upsert the first parameter, and ignores to upsert the rest of the parameters. Can someone kindly explain why this is happening?
Find below the events template, where the userId, password, email, names, parameters are passed onto the Meteor method regenerateApiKey in subject
/client/main.js
Template.apiKey.events({
'click .regenerate-api-key': function( ){
var userId = Meteor.userId();
var password = Meteor.user().services.google.accessToken;
var email = Meteor.user().services.google.email;
var names = Meteor.user().services.google.name;
alert("Password: " +password);
alert("email: " +email);
alert("email: " +names);
confirmRegeneration = confirm( "Are you sure? This will invalidate your current key!" );
if ( confirmRegeneration ) {
Meteor.call( "regenerateApiKey", userId, password, email, names, function( error, response ) {
if ( error ) {
alert( error.reason, "danger" );
} else {
+response );
alert( "All done! You have a new API key: " +response );
console.log("Response is: " +response);
}
});
}
}
});
The events template above renders 5 popup Alerts:
POPUP.1 Password: ya29.Glz
POPUP.2 email: centos.east#gmail.com
POPUP.3 email: Centos East
POPUP.4 Are you sure? This will invalidate your current key!
To which I press YES
POPUP.5 All done! You have a new API key: [object Object]
The code below illustrates the Meteor.call( "regenerateApiKey") along with the userId, password, email, names parameters.
/server/main.js
Meteor.methods({
regenerateApiKey: function( userId, password, email, names ){
check( userId, Meteor.userId() );
var newKey = Random.hexString( 32 );
var password = password;
var email = email;
var names = names;
console.log("password: " +password);
console.log("email: " +email);
console.log("names: " +names );
console.log("newKey: " +newKey);
try {
var keyId = APIKeys.upsert( { "owner": userId }, {
$set: {
"key": newKey,
"password": password,
"email": email,
"names": names
}
});
return keyId;
} catch(exception) {
console.log("FAILED UPDATE")
return exception;
}
}
});
In the terminal, I am able to see what is rendered by the code above:
password: ya29.Glz
email: centos.east#gmail.com
names: Cent East
newKey : 337829bb18082690a32f94a3c23b3782
When I query APIKeys.find().fetch() in the console, I get:
key: "337829bb18082690a32f94a3c23b3782"
_id:"PgBmn6zSYiXTbx6tu"
Which indicates that ONLY the newKey variable was set to key BUT the query ignored to set password, email, and names variables.
Can someone kindly explain why the password, email, and names variables aren't being set (included) in the collection?
The reason why only the key was being upsert in the query below:
APIKeys.upsert( { "owner": userId }, {
$set: {
"key": newKey,
"password": password,
"email": email,
"names": names
}
});
was actually false. The ENTIRE query was correctly being carried out.
The fault was in the Publish configuration itself!
The publish configuration ONLY allowed for the key fields value to be displayed!
Find below my Publish configuration code:
Meteor.publish( 'APIKey', function(){
var user = this.userId;
var data = APIKeys.find( { "owner": user }, {fields:
{
"key": true,
} });
if ( data ) {
return data;
}
return this.ready();
});
To correct this issue, I have had to re-configure my publish to the below code:
Meteor.publish( 'APIKey', function(){
var user = this.userId;
var data = APIKeys.find( { "owner": user }, {fields:
{
"key": true,
"password": true,
"email": true,
"names": true
} });
if ( data ) {
return data;
}
return this.ready();
});
I'd like to thank #Ivo in the thread for pointing me in the right direction in regards to this issue.

How to check email exists in firebase?

Hi I'm using firebase and javascript. I need to check for email id existing or not when new user signs up. This code works for user name or id, but shows error having email as record. I don't want to overwrite firebase unique key generation for each record.
var ref = new Firebase("https://kkk.firebaseio.com/");
var users = ref.child("users");
var userId = document.getElementById("email").value;
function checking()
{
checkIfUserExists(userId);
}
function userExistsCallback(userId, exists) {
if (exists) {
alert('user ' + userId + ' exists!');
} else {
alert('user ' + userId + ' does not exist!');
var check = users.push({ email: username});
}
}
function checkIfUserExists(userId) {
users.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}
I'm getting this error when I enter email.
Error: Firebase.child failed: First argument was an invalid path: "anu#gmail.com". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
I want my data in firebase to looks like this,
users:{
"ksjhfsjkbv67dsjhbcxcscdg":{
"email": "sdfs#gmail.com"
},
"kXdhbrurjw9974jjdsos_asd":{
"email": "anu#gmail.com"
},
...
Can someone help me?
If you're data in firebase has unique keys then it probably looks something like:
{
users:{
"dsjhfsjkbv67dsjhbcxcscdg":{
"email": "blah#whatever.com"
},
"sXdhbrurjw9974jjdsos_asd":{
"email": "anu#gmail.com"
},
...
}
}
the error your getting is because you cannot have illegal characters as the "keys" for your data so:
{
"anu#gmail.com": "email"
}
would not be acceptable hence the error:
Error: Firebase.child failed: First argument was an invalid path: "anu#gmail.com". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
the "." is not allowed.
One way to check if your value exists if you do not know the unique key is to do something like:
users.once('value', function(snapshot) {
var exists = false;
snapshot.forEach(function(childSnapshot){
if(userId === childSnapshot.val().email){
exists = true;
}
})
userExistsCallback(userId, exists);
});
you can read more about the for each function here:
https://www.firebase.com/docs/web/api/datasnapshot/foreach.html
I don't think you have to check if the email already has an account because firebase can not create another account with the same email.

Categories

Resources