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
}
}
I have an Api which is fetching Email and password. After that I am seeing if that email and password exists by the following functions:
function EmailCheck(Email){
return arr.some(function(el) {return el.attributes.Email === Email;})}
And same for password just changing email to password but if email is of one object and password ob another objects it passing. Is there any way I can check if Password is in Object where Email is.
what do you mean by another object its passing? do your objects look like this
emailObject = {
'email': 'some#email.com'
}
passwordObject = {
'password': 'password'
}
or like this
authObject = {
'email':'some#email.com'
'password': 'password'
}
if it is like the latter you could just use one function
authCheck(email,password){
return arr.some((el)=>{
if(el.email != email){
return false
}
return el.password == password
})
}
however this may not be the best approach. it kind of depends on what your database looks like and how everything is strung together but what i have done in the past is something like
checkUser(email, password){
return arr.find((user)=>{
return user.email === email && user.password === password
})
}
that way it finds the first (should be only) object, and returns it to be used. this will also allow you to get the index in the array if needed or do ther checks on the same object once you have gotten it. (like removing the password check and doing that as a separate function)
checkUser(email, password){
let user = arr.find((user)=>{
return user.email === email
})
if(user){
//do password check and other operations here
}
return user // for anything that needs to be done with the user
}
I run updateOne function inside a PUT request on the server, and apparently the function does not find the record, although it returns no error. The update does not happen.
Premises: I get an id field (not _id) inside the http request. The id is of the form <name>-stage-###. I want to change the value of the id to the same without the -stage-### part.
So I now have 2 strings: issueId which includes the 'stage' part, and bareIssue which does not.
I delete without checking the record with id = bareIssue (if it exists, it is deleted, and this part works fine).
Then I try to update the id field of the record with id=issueId, and change it to bareIssue. This does not work.
Other things that do not work:
adding or removing quotes from around the "id" or id field don't change anything
putting the $eq modifier in the query phrase doesn't change anything
Changing the id that I'm searching for to an id that does not exist doesn't change anything, in other words, if I try updateOne({id:"BLABLABLAFOOBAR"}, {$set: {id:"NiceID"}}), I still get success in the .then clause of updateOne.
adding a function to the updateOne and checking for error never gives an error.
Trying to use mongo ID instead of a string as the id doesn't work.
const dbConnection = mongoose.createConnection(DbServerLocation, options);
const db = dbConnection.useDb('issuesAndFiles');
const issuesModel = db.model(ISSUES_COLLECTION_NAME, reportSchema, ISSUES_COLLECTION_NAME); // In short - it is a model
router.put('/', (req, res, next) => {
let issueId = req.query['id'];
if (issueId) {
let bareIssue = issueId.substring(0, issueId.indexOf("-stage-"));
issuesModel.findOneAndRemove({id:bareIssue}).then(() => {
const query = {$eq: {id:issueId}};
const subst = {$set :{id:bareIssue}};
let retval = issuesModel.updateOne(query, subst)
.then(() => {
console.log("Put: success in updateOne");
res.status(200).send("Approved")
}
)
})
}
else {
res.status(404).send("Issue not specified")
}
});
I expected the document to be updated. It is not.
$eq syntax is wrong. Try { <field>: { $eq: <value> } }
Try with this -
const dbConnection = mongoose.createConnection(DbServerLocation, options);
const db = dbConnection.useDb('issuesAndFiles');
const issuesModel = db.model(ISSUES_COLLECTION_NAME, reportSchema, ISSUES_COLLECTION_NAME); // In short - it is a model
router.put('/', (req, res, next) => {
let issueId = req.query['id'];
if (issueId) {
let bareIssue = issueId.substring(0, issueId.indexOf("-stage-"));
issuesModel.findOneAndRemove({id:bareIssue}).then(() => {
/* const query = {$eq: {id:issueId}};
const subst = {$set :{id:bareIssue}}; */
const query = {id : {$eq: issueId}};
const subst = {$set :{id:bareIssue}};
let retval = issuesModel.updateOne(query, subst)
.then(() => {
console.log("Put: success in updateOne");
res.status(200).send("Approved")
}
)
})
}
else {
res.status(404).send("Issue not specified")
}
});
Thank you to all who tried to help.
My problem was this: my schema did not include the item "id", and it ran in strict mode. Apparently in Robo 3T the schema was updated by someone else, but not in the code. Stupid mistake which took me all day to figure out and fix. Don't let it happen to you:)
Note to people who look for the answer: if you have a variable for the model, such as this:
const issuesModel = db.model(ISSUES_COLLECTION_NAME, issueSchema, ISSUES_COLLECTION_NAME); make sure that the issueSchema item includes the name that you want to change.
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);
});
I'm running some project on MEAN.js and I've got a following problem. I want to make some user's profile calculation and the save it to database. But there's a problem with method in users model:
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
If I will send a password with my changes, it will change credentials, so user is unable to login next time. I want to delete password from user object before save, but I'm not able to do it (let's look at the comments in my code below):
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
/* Some calculations and user's object changes */
req.login(user, function(err) {
if(err) {
res.status(400).send(err);
} else {
console.log(delete user.password); // returns true
console.log(user.password); // still returns password :(
//user.save();
//res.json(user);
}
});
}
})(req, res, next);
};
What's wrong? Why the delete method returns true, but nothing happens? Thanks for your help :)
Just do:
user.password = undefined;
instead of:
delete user.password;
and the password property will not appear at the output.
there are certain rules for delete operator in javascript
if the property is an own non-configurable property in "strict mode" than it will return false.
for example
x = 42; // creates the property x on the global object
var y = 43; // creates the property y on the global object, and marks it as non-configurable
// x is a property of the global object and can be deleted
delete x; // returns true
// y is not configurable, so it cannot be deleted
delete y; // returns false
If the object inherits a property from a prototype, and doesn't have the property itself, the property can't be deleted by referencing the object. You can, however, delete it directly on the prototype.
for example
function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();
// returns true, but with no effect,
// since bar is an inherited property
delete foo.bar;
// logs 42, property still inherited
console.log(foo.bar);
so, please cross check these point and for more information your can read this Link
Had a similar problem. This worked for me:
// create a new copy
let newUser= ({...user}._doc);
// delete the copy and use newUser that thereafter.
delete newUser.password;
Working with MONGOOSE?
If you're facing this issue when working with Mongoose (Mongo DB's upper layer) then you can use lean property on find method
Examples
Without lean (The keys won't be deleted)
const users = await User.find({ role: 'user' }) // no lean method
users.forEach((user) => {
delete user.password // doesn't delete the password
})
console.log(users)
/* [
{name:'John', password:'123'},
{name:'Susan', password:'456'}
]
*/
With lean (The keys get deleted)
const users = await User.find({ role: 'user' }).lean()
users.forEach((user) => {
delete user.password // deletes the password
})
console.log(users)
/* [
{name:'John'},
{name:'Susan'}
]
*/
Reason why lean works
Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters, virtuals, or other Mongoose features.
Documents are kind of read-only, so delete doesn't work on them
Reference - https://stackoverflow.com/a/48137096/10824697
https://mongoosejs.com/docs/api.html#query_Query-lean
Method 2 without lean
If you want to use the mongoose provided method to remove some property while you are querying, you can remove with select method,
const users = await User.find({ role: 'user' }).select('-password')
console.log(users)
/* [
{name:'John'},
{name:'Susan'}
]
*/
The answer above from Majed A is the simplest solution that works for single objects properties, we can even make it for more easier by removing the ...user spreader. just delete the property from your object._doc sub-object. in your example it would have been:
user.save()
delete user._doc.password
res.status(201).json(user) // The password will not be shown in JSON but it has been saved.
Had a similar issue. The delete operator "was not working" when trying to delete a property from an object in a specific case. Fixed it using Lodash unset:
_.unset(user, "password");
https://lodash.com/docs/4.17.11#unset
Otherwise the delete operator does work. Just in case, delete operator docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
If password was defined with defineProperty, then configurable defaults to false if not set. In that case, then the property can't be deleted.
For me, node js still tells me the property was deleted (console.log(delete obj.prop)), but it wasn't deleting.
function test(settings) {
settings = {...{c: false, w:false}, ...settings}
let obj = {}
Object.defineProperty(obj, "prop", {
configurable: settings.c,
enumerable: settings.e ?? true,
writable: settings.w,
value: "foo"
});
console.log(
JSON.stringify(settings),
'\nset value to 1', (function() {obj.prop = 1})() || "",
'\nappended bar:', (function() {obj.prop += "bar"})() || "",
'\nobj:', JSON.stringify(obj),
'\ndelete:', delete obj['prop'],
'\nobj:', JSON.stringify(obj))
}
console.log('baseline: unchangeable, undeletable');
test()
console.log('unchangeable, deletable');
test({c: true})
console.log('changeable, undeletable');
test({w: true})
console.log('changeable, deletable');
test({c: true, w: true})
You may use this. It skips the unwanted key instead of deleting, it then returns an object.
let x = {1:'1', 2:2}
console.log('in', x)
function remove(Object, key){
let outputObject = {}
for (let inKey in Object){
if(key == inKey){
console.log(key , 'was deleted')
}else{
outputObject[inKey] = Object[inKey]
}
}
return outputObject
}
let out = remove(x, 1)
console.log('out', out)
The most likely, property which you want to delete has not owned the property for this object. In this case, the result of the operation will show true but nothing will be deleted.