String equality not producing expected output - javascript

I am trying to equate two variables for some other code but despite being the same string I keep getting false. Here is the code I wrote:
app.post('/deletegraph', requireLogin, async (req, res) => {
let {graph_name} = req.body
console.log(graph_name)
const user = await User.findById(req.session.user_id)
console.log(user.graphs)
for (let graph of user.graphs) {
console.log(graph[1])
console.log(graph_name)
console.log(graph[1] === graph_name)
}
res.redirect('/graphs')
})
And this is the output in the terminal:
xsquared
[
[ 'http://localhost:3000/', 'xsquared', '.png' ],
[ 'http://localhost:3000/', '2 exponent x', '.png' ]
]
xsquared
xsquared
false
2 exponent x
xsquared
false
As you can see my graph_name variable is equal to 'xsquared' and in the first iterance of user.graphs, graph[1] is equal to 'xsquared'. This should output true but I get false. Does anyone know what's wrong?
I used console.log so that I know what the variables are but even when I see that they are the same I get false. I've tried double equals and triple equals and they both give me false.

Related

Prisma/React Query Dependent undefined type challenges

I would like to take the output of one query (a TRPC query on Prisma) and use this as the dependent input in a future query.
I followed the dependent documentation for React Query but running into type errors that the return of the first may possibly be undefined (e.g. product is possibly 'undefined'):
const { data: product } = api.product.getUnique.useQuery({ id: pid });
const options = api.option.getAll.useQuery(
{
product: product.productSize,
region: product.productRegion,
},
{ enabled: !!product }
);
Does the inclusion of enabled not already handle this? If not, what is the correct way to adapt for Typescript.
Just casting the product value as a boolean return any truthy value (f.e if product will be equal to {} it will still result in true, that means that product won't necessarily have the productSize or productRegion properties, I would change it first to:
{ enabled: !!product && product.productSize && product.productRegion }
If that doesn't fix the typescript error, you as a developer can know for sure that the values are actually there so what you can use the as keyword in typescript to tell it that you know for sure that the type is what you want it to be:
(In this example I assumed that the values are string but you can change it to number or whatever the true value of them are)
const options = api.option.getAll.useQuery(
{
product: product.productSize as string,
region: product.productRegion as string,
},
{ enabled: !!product && product.productSize && product.productRegion }
);

I'm working with mongoose and nodejs, but not able to print what i want to

let somevar = candidate.find({}, {_id:0,name:1 });
console.log(somevar.map());
Current output which was not expected
Query {
...
collectionName: 'candidates'
},
_traceFunction: undefined,
'$useProjection': true,
_userProvidedFields: { _id: 0, name: 1 }
}
Im not able to understand the error, so want someone to explain me whats happening here.
What i expected it to do is
["name1","name2".....]
You are creating a query but not executing it. You need to either do:
let someVar = await candidate.find()
Or
candidate.find().exec(function(err, candidates){
console.log(candidates)
});

Loose equality in Mocha

In my test, I am passing an object that has two boolean values (among other values) to my API. I am then testing that the object was stored correctly in my database. The response should be exactly the same as the input, except that MySql stores booleans as integers.
I would like to test all of the fields without repetitive code, so I have written this:
const validChannel = {
id: `${new Date().getTime()}`,
major_nbr: 2,
minor_nbr: 1,
delivery: 'ATSC1',
display_nbr: '2.10',
opt_in: true,
visible: true,
callsign: 'TEST',
};
const channel = api.get();
Object.keys(validChannel).forEach((k) => {
expect(channel[k]).to.equal(validChannel[k]);
});
This works great, except that Mocha uses strict comparison, so 1 != true. How can I make this work while still keeping it compact?

How to perform date comparisons against postgres with sequelize

I want to delete all records with dates before 20 minutes ago. Postgres (or Sequelize) is not satisfied with the bare javascript Date object I provide as the comparison value.
I'm using sequelize 4.37 on top of a postgres 9.6 database.
The column in question was declared with type: Sequelize.DATE, which research suggests is equivalent to TIMESTAMP WITH TIME ZONE: a full date and time with microsecond precision and a timezone signifier. (That is also what I see when I use the psql CLI tool to describe the table.)
So, I do this:
const Sequelize = require('sequelize')
const { SomeModel } = require('../models.js')
// calculate 20 minutes ago
async function deleteStuff() {
const deletionCutoff = new Date()
deletionCutoff.setMinutes( deletionCutoff.getMinutes() - 20 )
await SomeModel.destroy({
where: {
[ Sequelize.Op.lt ]: { dateColumn: deletionCutoff }
}
})
But I get this error:
Error: Invalid value { dateColumn: 2018-11-21T21:26:16.849Z }
The docs suggest I should be able to provide either a bare javascript Date, or an ISO8601 string, but both throw the same Invalid Value error. The only difference is that, if I pass a string, the error shows single quotes around the value:
// error when dateColumn: deletionCutoff.toISOString()
Error: Invalid value { dateColumn: '2018-11-21T21:26:16.849Z' }
Well, this is pretty embarrassing. I structured the where clause incorrectly.
// BAD CODE
await SomeModel.destroy({
where: {
[ Sequelize.Op.lt ]: {
dateColumn: deletionCutoff
}
}
})
// GOOD CODE
await SomeModel.destroy({
where: {
dateColumn: {
[ Sequelize.Op.lt ]: deletionCutoff
}
}
})
Maybe I should delete the question. Maybe not -- the error I got probably could be more helpful.

DynamoDB putItem ConditionExpression "boolean" true

am trying to do a ConditionExpression in a DynamoDB put to check whether a stored boolean is true (in this example, whether the user is already verified don't run the put), i'm using the javascript DocumentClient SDK (thanks to #shimon-tolts), the code looks like:
var query = {
TableName: tableName,
Item: {
email: email,
verified: false,
verifyToken: token
},
ConditionExpression: 'attribute_exists(email) AND verified = :bool',
ExpressionAttributeValues: {
":bool":"false"
}
};
dynamodb.put(query, function(err, data){
if (err) return fn(err)
fn(null, data);
});
Which doesn't work, it fails the condition check no matter what the call.
Pretty much what I need (in pseudocode):
IF email already exists AND verified equals false
THEN allow PUT
IF email already exists AND verified equals true
THEN don't allow PUT
IF email does not exist
THEN allow PUT
Any ideas?
I suggest using DocumentClient as it works with javascript objects.
To do a condition expression you have to specify the ExpressionAttributeNames and ExpressionAttributeValues for example::
ConditionExpression: "#yr <> :yyyy and title <> :t",
ExpressionAttributeNames:{"#yr":"year"},
ExpressionAttributeValues:{
":yyyy":year,
":t":title
}
You can see more examples here and read more here
I finally got this to work after figuring out the right ExpressionAttributeValues:
dclient.scan(TableName='bix-workflow-images',
FilterExpression="wgs = :t or attribute_not_exists(wgs)",
ExpressionAttributeValues={':t':{'BOOL':True}})
I am stumbling about this because I have a similar problem and although this is a year old, for me it looks like your boolean shouldn't be a string:
ExpressionAttributeValues: {
":bool": "false"
}
Instead:
ExpressionAttributeValues: {
":bool": false
}
Have you tried it that way?

Categories