I am attempting to port an application that had used sequelize 3.30.4 and I'm updating to 6.13, I'm assuming some things have changed because I can't use string literals in a where clause, or so the debugger tells me.
That said, I've done some googling and have found some basic examples that make sense sure but I'm not entirely sure how to convert this string to a format acceptable for findAndCountAll to be happy.
I've attempted something like this, thinking it might at least point me in the right direction however it does not.
let attributes = ['id', 'name', 'locationId'];
let where = undefined;
let order = [['name', 'ASC']];
where = {
classroom: {
locationId: request.query.locationId
}
}
this is the line that did at one time work but no longer works.
where = `"classroom"."locationId" = ${request.query.locationId}`;
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where: where ? [where] : undefined,
order
}));
how would I go about porting this into the proper format?
Try something like this:
let where = {}
if (<some condition>) {
where = {
locationId: request.query.locationId
}
}
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where: where,
order
}));
You can also try that even if the first comment of ANATOLY works wonders :
const where = <some condition> ? {locationId: request.query.locationId} :{};
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where,
order
}));
Related
I have a method called populateProvidedValuesForNewMandate that looks like this
exports.populateProvidedValuesForNewMandate = (team, assignee, disputeValue, lawField,
subjectOfDispute, party, fileReference, costUnit, clientUnit, sideEffect, comment) => {
const teamInput = element(by.css('div#team input'));
const assigneeInput = element(by.css('div#assignee input'));
const disputeValueInput = element(by.id('dispute_value'));
const lawFieldInput = element(by.css('div#law_field input'));
const subjectOfDisputeInput = element(by.id('subject_of_dispute'));
const partyInput = element(by.id('party'));
const fileReferenceInput = element(by.id('file_reference'));
const costUnitInput = element(by.css('div#cost_unit input'));
const clientUnitInput = element(by.id('client_unit'));
const sideEffectInput = element(by.css('div#side_effect input'));
const mandateComment = element(by.id('mandate_comment'));
// TODO: Figure out how to choose these dynamically as well
// relevantCase, risReportRelevant, economicRelevance, activePassive
const relevantCaseInput = element(by.css(".relevant_case input[value='no']"));
const riskReportRelevantInput = element(by.css(".risk_report_relevant input[value='no']"));
const economicRelevanceInput = element(by.css("label[for='economic_relevance']"));
const activePassiveInput = element(by.css(".active_passive input[value='passive']"));
teamInput.sendKeys(team);
assigneeInput.sendKeys(assignee);
disputeValueInput.sendKeys(disputeValue);
lawFieldInput.sendKeys(lawField);
subjectOfDisputeInput.sendKeys(subjectOfDispute);
partyInput.sendKeys(party);
fileReferenceInput.sendKeys(fileReference);
costUnitInput.sendKeys(costUnit);
clientUnitInput.sendKeys(clientUnit);
sideEffectInput.sendKeys(sideEffect);
mandateComment.sendKeys(comment);
// TODO: Figure out how to choose these dynamically as well
// relevantCase, risReportRelevant, economicRelevance, activePassive
browser.actions().mouseMove(relevantCaseInput).doubleClick().perform();
browser.actions().mouseMove(riskReportRelevantInput).click().perform();
browser.actions().mouseMove(economicRelevanceInput).click().perform();
browser.actions().mouseMove(activePassiveInput).click().perform();
};
and here is an example of its use case
values.populateProvidedValuesForNewMandate(texts.DISPUTE_VALUE, texts.PARTY, texts.CLIENT_UNIT,
texts.SIDE_EFFECT, texts.COMMENT);
The method fills out the specified values that lie within a file called texts.js into the appropriate fields. The problem is that I get the error message: 'each key must be a number of string; got undefined' meaning that this method doesn't work because I have to send the keys for each specified variable in the method.
I really want to avoid sending empty strings for this method (especially because it won't work, I've tried it out -> I get a error from the app itself, not protractor/selenium).
How can I turn this method into one that only considers the specified variables in the test cases.
Also as you can see from my comment, I am trying to figure out how to do this for the checkbox and radio buttons as well. If anyone has a hint, I'd really appreciate it
Honestly, only you can answer the question. Because there are hundreds of ways to fo this, and some may work better than another. So to us it's silly to make guesses which way is the best for you. So I'll give one example and hopefully you can take it from here
One way is to make the method accept an object and check if a property has been passed
function fillForm(obj) {
if (obj.hasOwnProperty('team')) teamInput.sendKeys(team);
if (obj.hasOwnProperty('assignee')) assigneeInput.sendKeys(assignee);
if (obj.hasOwnProperty('disputeValue')) disputeValueInput.sendKeys(disputeValue);
// ...
}
and then call it
fillForm({
assignee: texts.ASIGNEE,
disputeValue: texts.DISPUTE_VALUE
})
so it will skip sending keys to team field
Here is some code from I project I am working in:
const profile = userdataDocs
.filter(isValidUserdataDocument)
.find((document: ICouchDBDocumentDoc) => document._id === profileId);
if (profile) {
return {
id: hashSensitive(profile._id, environment),
type: profile.type,
creationDate: profile.creationDate,
updatedDate: profile.updatedDate,
entityVersion: profile.entityVersion,
};
}
Here is how I would like to have my code look:
return userdataDocs
.filter(isValidUserdataDocument)
.filter((document: ICouchDBDocumentDoc) => document._id === profileId)
.map((profile: ICouchDBDocumentDoc) => ({
id: hashSensitive(profile._id, environment),
type: profile.type,
creationDate: profile.creationDate,
updatedDate: profile.updatedDate,
entityVersion: profile.entityVersion,
}))
.slice(0, 1);
But I get feedback from the rest of my team that I should not use filter because it will continue searching after having found an item. Premature optimization in mind, but still a pretty valid and popular opinion.
Is there some other array method (or altogether different solution) that I can use to write code the way I want, with 'pipes', without getting the performance penalty of moving from find to filter?
Also let me know if I am an idiot and should let go of the pipe dream (pun intended).
Let me start that I like the first solution. In my opinion, it looks good.
But if you are really desperate for a solution that fulfills your pipe dream
const array = [10, 20, 30];
function singleMapFind(args, fn) {
const currentArray = args[2];
const duplicate = [...currentArray];
currentArray.splice(1, currentArray.length - 1);
return duplicate.find(fn);
}
const modified = array.map((...args) => singleMapFind(args, (e) => e > 20));
I would never use it though. Wish you luck with the PR.
Trying to search through my mongoDB database using variable names not by specifying the exact search. Is it possible to do this? No matter how i try to format the variable I can't get a successful search. I'm trying to do something like the bottom line below
let url3 = 'http://cs544.io/11jgry2';
const ret = await dbTable.find({"shortUrl" : "http://cs544.io/11jgry2"}); //Works
const ret = await dbTable.find({"shortUrl" : url3}); //Doesn't work
Use $eq it Specifies equality condition. The $eq operator matches documents where the value of a field equals the specified value.
Check this this for further explanation and examples
Theoretically, it should work,
But I suggest having a look into using $eq instead.
Here is an example
const ret = await dbTable.find( { shortUrl: { $eq: url3 } } );
I want to sort an Array depending on a Boolean, but only if a second condition is true.
I can sort the Array by Boolean like this (I know you could also leave out the if part, but I wanted to see if it works like this.
posts = sortBy(posts, [function(post) {
if (post.featured_post === true) {
return post
}
}]);
But now I would like to add another condition:
posts = sortBy(posts, [function(post) {
if (post.featured_post === true && post.date >= today) {
return post
}
}]);
But this does not seem to work anymore. I get pretty random orders.
Maybe I also don't understand how to use the sortBy with a function, so some help is highly appreciated.
PS: I don't get any errors, it just does not sort correctly.
Cheers
Because of #gforce301 s question I realized that I never transformed the event date into a javascript Date object. By doing this:
const today = new Date().setHours(0,0,0,0)
posts = sortBy(posts, [function(post) {
const postDate = new Date(post.date).setHours(0,0,0,0)
if (post.featured_post && postDate >= today) {
return post
}
}])
I actually got the sortBy to work – even with branch statements. Good to have another example of how lodash's sortBy works.
Thanks for your help. Cheers
Your solution works a bit by random and I think it will be hard to understand / adapt.
What about this one?
import { get } from 'lodash/fp'
import { overEvery, sortBy, negate } from 'lodash'
const shouldBeFirst = overEvery(
get('featured_post'),
({ date }) => (new Date(date).setHours(0,0,0,0)) == (new Date().setHours(0,0,0,0))
)
const preSortedPosts = sortBy(posts, 'date')
const sortedPosts = [
...preSortedPosts.filter(shouldBeFirst),
...preSortedPosts.filter(negate(shouldBeFirst))
]
Hi I have the following object structure,
const usersList = {
NFr9F4WbBxR4H5ajolbS6q0skPF2: {
name: "justin davidson",
uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2"
},
asas9F4WbBxR4H5ajolbS6q0sasF2: {
name: "sawyer davidson",
uid: "asas9F4WbBxR4H5ajolbS6q0sasF2"
}
}
It has a user ID as key, and it's user object nested within. I want to store the inner user data. I've been using Ramda JS and have done so by doing the following,
let x = []
const y = R.keys(usersList).forEach((uid) => {
x.push(usersList[uid])
return x
})
which returns
[{"name":"justin davidson","uid":"NFr9F4WbBxR4H5ajolbS6q0skPF2"},
{"name":"sawyer davidson","uid":"asas9F4WbBxR4H5ajolbS6q0sasF2"}]
..however I'd like achieve the same in a purely functional way. What would be the best approach here? I'm guessing compose and map but I can't seem to work it out. Looking for a little direction.
Thanks
Just use map instead of forEach:
const x = R.keys(usersList).map((uid) => usersList[uid])
It looks like there's also a values method that does what you want:
const x = R.values(usersList)
There isn't always a function tucked away in some lib that does exactly what you want it to do. Showing how to do things on your own demonstrates that you don't have to feel "stuck" when you're faced with a problem and you can't find a magical function to solve it for you. Once you learn the function exists, sure, go ahead and replace your home-brew solution with the built-in. But until then, don't be afraid to write code and move on.
// ovalues :: (Object k:v) -> [v]
const ovalues = o =>
Array.from(Object.keys(o), k => o[k])
const usersList = {
NFr9F4WbBxR4H5ajolbS6q0skPF2: {
name: "justin davidson",
uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2"
},
asas9F4WbBxR4H5ajolbS6q0sasF2: {
name: "sawyer davidson",
uid: "asas9F4WbBxR4H5ajolbS6q0sasF2"
}
}
console.log(ovalues(usersList))
So yep, R.values does exist in the Rambda library, but next time don't be afraid to try to solve it on your own. You have a powerful brain, now use it ^_^