Detect value of child changed from false to true - javascript

How can I detect if the value of the child i.e. userStatus is changed from false to true in firebase database.
Below is the code that I trying to use, but it doesn't work. As, I understand, when the userStatus is changed from false to true, the below expression is no longer true and hence doesn't get triggered.
Can someone please suggest, how I could achieve this ?
usersRef.orderByChild("userStatus").equalTo(false).on("child_changed", function(snapshot) {
var userDetails = snapshot.val();
var firstname = userDetails.firstName;
console.log("userDetails, firstname: "+firstname);
});
[EDIT]
Below is my firebase db structure, where I am trying to trigger a child_changed event only when the userStatus changes from false to true.

One solution would be to use a query that matches users with a userStatus of false and to then listen to the child_removed event. You will be notified when a user changes and no longer matches that query. That is, you will be notified when the userStatus changes from false to true.
usersRef.orderByChild("userStatus")
.equalTo(false)
.on("child_removed", function (snapshot) {
var userDetails = snapshot.val();
var firstname = userDetails.firstName;
console.log("userDetails (status changed to true), firstname: " + firstname);
});

Related

Login system that checks out if the user already has an account. If they have one then they get to login, if they don't then they must try again

My overall problem is actually finding the values of the variables ''loginEmail'' and ''loginPass'' inside my ''arrayRegistros''. It only becomes TRUE when I write the email and password inside includes manually, however, it always ends up turning into FALSE when I use the variables themselves. I tried converting the variables into strings, then used document.getElementById alongside a few other ideas but until now, none of them completed the login system I had planned. The help I need is how one can find a certain variable's value/object, inside a certain array.
login(registro){
this.arrayRegistros;
var loginEmail = document.getElementById('userEmail');
var loginPass = document.getElementById('userPass');
var contaEmail = this.arrayRegistros.some((loginEmail) => {
return loginEmail.emailRegistro.includes(loginEmail)
})
var contaPass = this.arrayRegistros.some((loginPass) => {
return loginPass.passRegistro.includes(loginPass)
})
console.log(contaEmail)
console.log(contaPass)
}
you should get values from inputs like this:
const data = [
{
user : 'jhon',
password : 'asdf123'
},
{
user : 'bob',
password : 'asdf124'
}
]
const userName = document.getElementById('userEmail').value;
const passWord= document.getElementById('userPassword').value;
const findUser = data.filter( item => item.user === userName && item.password === passWord);
if(findUser.length > 0){
//user found
}
The first problem is that you are naming the parameter on the Array.prototype.some function the same as the variable you want to check outside of the predicate scope.
Second, suposing that this.arrayRegistros is a array with objects with the keys emailRegistro and passRegistro containing strings, DOM Elements CANNOT match with strings, but a element.value can.
Another thing you should have in mind is that includes is not an equality operator, 'a-very-strong-password'.includes('a'); will return true.
And, last, you should never validate login and password on the browser, because the user can edit the JavaScript code on-the-fly and get to login without any real credential.
With that in mind, I think the solution would be something like that (ignoring the browser validation problem):
const $userField = document.getElementById('userEmail');
const $passField = document.getElementById('userPass');
const registros = [
{
email: 'example#example.com',
password: 'a-very-strong-password'
},
...anotherUsers
];
function login(registro) {
const { value: user } = $userField;
const { value: pass } = $passField;
// You can use `Array.prototype.some` to just know if the specific user credentials exist, or use `Array.prototype.find` to know if exist AND grab the user, to further utilization
const item = registros.find(item => item.email === user && item.password === pass);
if (item) {
// User found
} else {
// User not found
}
}

How to use cloud function trigger based on two collections documents

I have a collection ReferalCodes in which each document is specified has these values where 'mine' value is false 'msg' value is false and mycode is user referal codes.
appliedcode: ""
mine:false
msg:false
mycode:"ASDF4G"
referals : []
And User has one more collection UserTransaction which have a field 'CountTrans' which is initialized as 0 when this value is 1 i want to trigger a function to check value of mine and appliedcode if the value of mine is true then and applied code have value of length 6 then i want to update the UserTransaction of that user and the appliedcode is referal code of some another user want to change UserTransaction of that user also
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { user } = require('firebase-functions/lib/providers/auth');
admin.initializeApp();
const db = admin.firestore();
exports.getCount= functions.firestore
.document('UserTransactions/{id}')
.onUpdate((change, context) => {
const newTransdata = change.after.data();
const previousTransData = change.before.data();
const docid = context.params.docid;
if(newTransdata.CountTrans === 1) {
const referalData = await
admin.firestore.collection('ReferalCodes').doc(docid).get()
const mine = referalData.mine;
const appliedCode = referalData.appliedCode;
let codes = [];
var myfrindid;
if(mine === true && appliedCode !== null) {
const friendData = await
admin.firestore.collection('ReferalCodes').doc('codes').get();
var referalcodes = friendData['ReferalCodes'];
referalcodes.forEach((items) =>{
if (items['code'] == appliedCode) {
myfrindid = items['id'];
}
});
await
admin.firestore.collection('ReferalCodes').doc(docid).update({
msg: true
})
}else{
}
}
});
Consulting the official documents is explained how to handle events on your database and trigger some different kind of triggers depending on your needs, for example:
onWrite(), which triggers when data is created, updated, or deleted in Realtime Database.
onCreate(), which triggers when new data is created in Realtime Database
onUpdate(), which triggers when data is updated in Realtime Database
onDelete(), which triggers when data is deleted from Realtime Database
For example, the first argument passed your onUpdate handler function is a Change object, this object has two properties, before and after, both DataSnapshot objects. These DataSnapshot objects describe the contents of the database before and after the change that triggered the function.
exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
const before = change.before // DataSnapshot before the change
const after = change.after // DataSnapshot after the change
})

How to get isModified to be true in mongoose with Node

I'm hashing passwords on a pre hook with mongoose schemas, however, the check I'm doing for isModified to know whether or not I should hash/rehash the password with isModified is always resulting in false.
await mongoose.connect(this.connUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
const oldUser = await UserModel.findOne({ name: user.name });
oldUser.name = user.name || oldUser.name;
oldUser.password = user.password || oldUser.password;
oldUser.firstName = user.firstName || oldUser.firstName;
oldUser.lastName = user.lastName || oldUser.lastName;
oldUser.email = user.email || oldUser.email;
oldUser.status = user.status || oldUser.status;
let modified = oldUser.isModified(); // test for seeing if modified or not. Always false
await oldUser.save();
result.status = status;
result.result = oldUser;
await mongoose.disconnect();
An fyi user is passed into the method housing this. I would've thought that by changing the properties it would be marked as isModified === true so how does one get the isModified set to true/false or what actually sets it? Any tips, suggestions, or advice appreciated. Open to a different way of doing this too, thanks!
Edit - based on comments and suggested similar answer
Even with the specified object parameter my code is still only presenting as false instead of true in the isModified() method. So the suggested questions isn't helpful because it doesn't answer how the modified property gets set in the first place.
If one uses oldUser.set('password', user.password || oldUser.password); for each of the properties then the object gets isModifed() === true however, when you set it directly with document.property = 'some value' then the object doesn't get isModified() === true but insetad is false, even though it did change the property, and will save it in the DB with .save(). So why is that, and what's the better way to update a document with mongoose?
I've made a full working example from scratch to test this, you can find the repo here:
https://github.com/ZeldOcarina/mongoose-edit-example
The main takeaway is this handler:
app.patch('/user', async (req, res) => {
const { id, username, password } = req.body;
const user = await User.findById(id);
user.username = username ? username : user.username;
user.password = password ? password : user.password;
await user.save();
res.status(200).json(user);
});
If a value exists it means something came from the form thus it's changed, let me know if this works for you or I dig further into this.
The Solution is why not using conditional about changing property. Example if u want to check password isModified like this :
oldUser.pre('save', function(next) {
if(oldUser.password && oldUser.isModified('password')){
this.password = bcrypt.hashSync(oldUser.password, bcrypt.genSaltSync(8),null);
}
next() });

indexeddb put not update a value, it creates a new (id)

I have a table with form, surname, lastname, email and a rectangle. I have to insert, in the rectangle, an array with arrays with points of timelines etc. I create a customer with form, surname, lastname and email, add them to indexeddb, load them later to insert the rectangle-array. After that, I want to put the newobjectstore in the indexeddb where the email is the same from my customer I choose/inserted. But with this code my array will be put in a new Objectstore with its own ID.
function cmd_SaveRec(hypeDocument, elementID)
{
hypeDocument.getElementById('rectext').innerHTML = hypeDocument.getElementById('beschriftung').value;
var store_cust = db.transaction(["customer"], "readwrite").objectStore("customer").index("rectangle");
var cursorReq = store_cust.openCursor();
cursorReq.onsuccess = function (e) {
cursor = e.target.result;
if(cursor) {
if(cursor.value.email == mailAdd)
{
//cursor.update([rec_ar]);
if(store_cust.objectStore.put({rectangle: [rec_ar]}))
{
console.info(store_cust.objectStore);
console.info('Gespeichert');
alert("Gespeichert");
} else {
console.info('cmd_SaveRec::Problem');
}
}
cursor.continue();
}
};
cursorReq.onerror = function(e) {
console.log("Error");
console.dir(e);
}
}
var store_cust = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME_CUSTOMER, { keyPath: 'cust_id', autoIncrement: true });
store_cust.createIndex('form', 'form', { unique: false }); //
store_cust.createIndex('surname', 'surname', { unique: false });
store_cust.createIndex('lastname', 'lastname', { unique: false });
store_cust.createIndex('email', 'email', { unique: true });
store_cust.createIndex('rectangle', 'rectangle', { unique: false, multiEntry: true });
Short answer
Provide an identifier/key as a second parameter in objectStor.put(data, key) or
Use a IDBCursor und update it as stated here in the docs
Explanation
As described in the docs:
The put() method of the IDBObjectStore interface updates a given record in a database, or inserts a new record if the given item does not already exist. (source developer.mozilla.org)
Your used method objectStore.put() is for insert or update tasks. If I get you right you're looking for an update - cursor.update() is your friend here (you commented out). - This is the preferred method here !
But you could do it with both methods. Say you would like to update but if the record not exists create one. In such a case the engine have to know if your record exists and what record do you try to update.
If your objectStore uses an autoIncrementing primary key the identifier of the record is not in the record itself so you have to provide the id as a second parameter to your put() function.
I find it easier to take care of the ids by myself. Then the id is part of the record (findable under the keypath you provided at objectStore-creation). Then your code could work as expected... certainly you have to add a key:value pair for an id.
Examples
// create a store with ids YOU handle e.g.
var request = indexedDB.open(dbname, dbversion+1);
request.onerror = errorHandler;
request.onupgradeneeded = function(event){
var nextDB = request.result;
if (!nextDB.objectStoreNames.contains('account')) {
nextDB.createObjectStore('account', {keyPath: "id", autoIncrement: true});
}
}
// Your record has to llok like this
{id: 123456789, rectangle: [rec_ar]}
// Now your code above should work
If you have a primary key in your db:
store_cust.objectStore.put({rectangle: [rec_ar]}, PRIMARY_KEY)
// where PRIMARY_KEY is the id of this specific record
By the way
Don't use if-else to check the completness of the transaction - it is asynchronus - if/else lies everytime here - use callbacks as I stated in my example above (onsuccess).
You should read the docs from my cite. Mozilla is a great ressource for indexedDB stuff.

Meteor Users collection and Deps.autorun problems

I'm still struggling to understand how to access Meteor.users as a foreign key from another collection query. I understand that only the current user is published by default so I have a publication on the server as
Meteor.publish('itemOwner', function(userId) {
check(userId, String);
var user = Meteor.users.find({id: userId});
return user;
// return Meteor.users.find({id: userId}, {
// fields: {'profile': 1} });
});
I then have a Deps.autorun on the client..
Deps.autorun(function () {
var itemOwnerId = Session.get("itemOwnerID");
if (itemOwnerId) {
debugger
var ID = Session.get("itemOwnerID");
Meteor.subscribe('itemOwner', Session.get("itemOwnerID"));
}
});
I set the session ID on a modal form load, and display it in the template by calling the ownerProfile helper (or try to)
Template.showQuoteModalInner.helpers({
getQuote: function () {
// Get the quote ID from the session var
var quote = Session.get("quoteID");
if(quote) {
debugger;
var ID = quote.user._id;
Session.set("itemOwnerID", quote.user._id);
return quote;
}
},
ownerProfile: function() {
debugger;
var quote = Session.get("quoteID");
if(quote) {
var ID = quote.user._id;
var theUser = Meteor.users.find({_id: quote.user._id});
return theUser;
};
}
});
Now, I can trace the user ID at each stage and see it getting correctly passed to the autorun and the helpers. If I stop the program at the debugger in the ownerProfile helper and in the console put in Meteor.user.fetch({_id: "the id here"}).fetch() I get the correct user back.. but, in the handler itself the Meteor.users.find returns null??? What am I missing?
Two possibilities I noticed.
First, you are missing an underscore in the find in your publish function.
.find({id: userId}) should be .find({_id: userId}).
But this probably isn't the issue if you are seeing the user (other than the logged in user) in the console.
Second, if you are not seeing the user from your Template.showQuoteModalInner.ownerProfile helper, it is probably because you are returning a find() instead of a findOne().
find() returns a cursor whereas findOne() returns the record. Try findOne() if you want to display that single user's attributes.

Categories

Resources