Mongoose Chained Queries - javascript

I'm currently reading this excellent MDN tutorial.
There seems to be two main different ways to perform queries with mogoose, one being more 'functional', using a chained notation.
My question is, does this kind of notation starting with an empty .find() method starts to import all the collection, then filters the successive pointers inside the app, or does it compile the query (the filtering stuff happening on the mongoDB instance) and only performs the callback locally?
The dot-based notation looks nice and cleaner, but if the filter does not get compiled before requests are being made it seems to be a bad idea to import the whole collection on the app for every simple query. Am I right?
If this is the case, are we in one of these situation where we have to favour object composition over function composition (like Eric Elliott said), or is it not the point here?

Related

Using ES6 Classes with Redux

I'm working on a project that brings in a ton of data from one endpoint into a a single reducer. I'd like to convert that data in ES6 Classes, so I can give them helper method, provide relations between the data, and not have to work with plain javascript objects all the time. Also, to get relations between the data, I'm having to do n-squared computations and that's slowing down the frontend.
Here are the options I'm seeing:
1) Create a selector that connects with the redux store. This selector could get the data from the reducer and convert it into multiple ES6 classes that I've defined. If the reducer gets new data that is different, then the selector will recreate the ES6 class instantiations.
2) https://github.com/tommikaikkonen/redux-orm
This seems fantastic as well.
3) Create multiple selectors on the data set to that will compute a specified relation in the data set, so I can just call that selector each time I want to get a relation that would otherwise be an n-squared computation to get.
My question is which route of the three should I take? Is there an alternative besides these 3? Or do people just work with javascript objects mostly on the frontend and not deal with ES6 classes.
Update:
Two months later, and I'm still using Redux-ORM in production and it is fantastic! Highly recommend.
It's certainly entirely possible to do all that handling with "plain" functions and selectors. There's info on normalization in the Redux FAQ, and I have some articles on selectors and normalization as part of my React/Redux links list.
That said, I am a huge proponent of Redux-ORM. It's a fantastic tool for helping manage normalized/relational data in your Redux store. I use it for normalizing nested data, querying data, and updating that data immutably.
My Practical Redux blog post series includes two articles talking about Redux-ORM specifically: Redux-ORM Basics and Redux-ORM Concepts and Techniques. The latest post, Practical Redux Part 5: Loading and Displaying Data, shows Redux-ORM in action as well.
The author of Redux-ORM, Tommi Kaikkonen, actually just put up a beta of a major update to Redux-ORM that improves the API and behavior, which I'm looking forward to playing with.
I definitely recommend it!

Backbone design patterns similar to DAOs

Overall I'm happy with using Backbone.js for my company's frontend application. However I've noticed a lot of foundational problems that I wonder if anyone else encountered.
The biggest issue is that the frontend team does not control the API that powers our application. The objects passed are fairly complex in structure. Nested arrays, sub objects, etc.... This of itself is expected. The API serves a different purpose than the frontend. What each considers an "object" are completely different things.
In practice this leads to issues. Namely, one API endpoint may be broken into multiple frontend models. This is a common problem when dealing with APIs. It's typically addressed through Data Access Objects or a Data Access Layers that translate API objects into internal objects. Backbone by contrast expects models to be tightly coupled with the API endpoints. Sync operations on a model (i.e. save, fetch) immediately reach out to the API.
Adding to the issues, I seriously believe that toJSON in Backbone does too much. It's used to reproduce the model in a format that can be consumed internally; defines how the model should get posted to an API; and used for equality checks between models for many internal operations. Any of the three could get broken out into their own method.
Has anyone else dealt with this? What strategies did you use? Implement DAOs? Is there a fork of Backbone that accounts for these issues?
[edit]
A closer to real world case that I've encountered. When we query the API for results, there's about a hundred filters we can pass along with the request. The overall filter structure is pretty simple on that end an array of filter objects like so:
{
filterName: '',
// '~', '=', '<=', '>='
operator: '',
value: ''
}
For one particularly problematic filter, depending on the 'operator' we either allow the user to select a single option or we allow the user to construct a "sentence" from the available options. The former option renders as an HTML select, the latter we implemented with a lextree parser. Obviously the two necessitate wildly different code so we split this into two different classes, but to the API the filter is the same regardless of our implementation.
This is straightforward enough, but issues with Backbone come into how the classes are defined. We may want to make use of the built-in get/set functions. But this will dump properties into attributes, which affects the default toJSON which is also used to build the API representation of this filter, and whether this filter is equal to another filter of the same type.
With a Data Access pattern there'd be another layer that knew how to translate that filter to the API and vice versa. Any CRUD operation would get picked up by the specific DAO and processed by proxy.

What's the relationship between streamjs and linqjs

After reading SICP, I recently discovered streamjs. The developer referenced linqjs as an alternate implementation with different syntax, but I can't make the connection. How do the methods in streamjs map to those in linqjs?
I haven't used either library, but, here's my initial analysis (I've read quite a bit of SICP, but not the whole thing admittedly).
stream.js is an implementation of a functional style data structure for a list. Many data structures in a functional language tend to be recursive, much like the Stream structure. It is composed of a head element, and a Stream for the tail (subsequent elements). Here, lazy evaluation can be achieved by allowing the tail to be a function (i.e. infinite sequences).
Now, to answer your question, all of the functions provided by linq.js should be able to be defined with other common higher order functions like map, reduce, walk, fold, etc.
Sure, stream.js does not implement the Any() method from linq.js, but you can just do that with reduce().
I guess they are similar because they pass functions around instead of "scalar values" ,so they can do lazy evaluation ( evaluate the result at the end of the operations / on demand and not at each operation like with classic javascript data structures). I used that principle with my pimple.js library , which has nothing to do with stream or link but uses lazy evalutation.
linq.js and stream.js have the following similarities:
Use functions to implement streams as a data structure
Use streams to implement lazy evaluation of operations
linq.js and stream.js have the following differences:
linq.js has syntactic sugar for querying JSON
stream.js has the ability to chain streams
linq.js has syntactic sugar for set operations
References
LINQ in JavaScript for Real
LINQ in JavaScript, ES6 Style

How to properly structure a KnockoutJS application

I am wondering how to structure a KnockoutJS application the right way.
The official documentation almost always uses just one single ViewModel!
After only a few implemented functions my code became very confusing and coming from an object-oriented background I am very allergic to architecture like that. So there must be a better solution.
Being not very experienced with JavaScript I was searching Stackoverflow and found those three options. So I tried the first two options and I am not happy with them:
Having multiple ViewModels like here.
I find it very difficult to decide what DOM-element gets what ViewModel. Also there were several functions called from outside the DOM-element. Maybe I used too little ViewModels with this kind of architecture but communicating between ViewModels seemed to be different and somehow shouldn't be necessary I hope. So how to do that properly?
Having sub views and utilizing the with binding (the second option from those three).
This was my preferred type of architecture because you can have document-wide bindings out of one view model but you can also structure your code into sub-chunks and bind them to wherever you want by using the with binding. This option though requires object literals instead of functions, which are inferior as described in this answer.
I haven't tried method three because it seems a little overkill and also uses object literals.
So is there a method to structure my code and also have full control without using object literals?
I hope this was not too confusing :-P
For any of the options that you mentioned, you do not need to use object literals. The samples just used them to simplify the code. You can choose to create the individual view models in any way that you see fit.
For example in #3, you can use a constructor function like: http://jsfiddle.net/rniemeyer/PctJz/149/. Of course, the actual data would get passed into the function rather than being static. Same with #2, you just would have it wrapped in the "View" object.

How can I write reusable Javascript?

I've started to wrap my functions inside of Objects, e.g.:
var Search = {
carSearch: function(color) {
},
peopleSearch: function(name) {
},
...
}
This helps a lot with readability, but I continue to have issues with reusabilty. To be more specific, the difficulty is in two areas:
Receiving parameters. A lot of times I will have a search screen with multiple input fields and a button that calls the javascript search function. I have to either put a bunch of code in the onclick of the button to retrieve and then martial the values from the input fields into the function call, or I have to hardcode the HTML input field names/IDs so that I can subsequently retrieve them with Javascript. The solution I've settled on for this is to pass the field names/IDs into the function, which it then uses to retrieve the values from the input fields. This is simple but really seems improper.
Returning values. The effect of most Javascript calls tends to be one in which some visual on the screen changes directly, or as a result of another action performed in the call. Reusability is toast when I put these screen-altering effects at the end of a function. For example, after a search is completed I need to display the results on the screen.
How do others handle these issues? Putting my thinking cap on leads me to believe that I need to have an page-specific layer of Javascript between each use in my application and the generic methods I create which are to be used application-wide. Using the previous example, I would have a search button whose onclick calls a myPageSpecificSearchFunction, in which the search field IDs/names are hardcoded, which marshals the parameters and calls the generic search function. The generic function would return data/objects/variables only, and would not directly read from or make any changes to the DOM. The page-specific search function would then receive this data back and alter the DOM appropriately.
Am I on the right path or is there a better pattern to handle the reuse of Javascript objects/methods?
Basic Pattern
In terms of your basic pattern, can I suggest modifying your structure to use the module pattern and named functions:
var Search = (function(){
var pubs = {};
pubs.carSearch = carSearch;
function carSearch(color) {
}
pubs.peopleSearch = peopleSearch;
function peopleSearch(name) {
}
return pubs;
})();
Yes, that looks more complicated, but that's partially because there's no helper function involved. Note that now, every function has a name (your previous functions were anonymous; the properties they were bound to had names, but the functions didn't, which has implications in terms of the display of the call stack in debuggers and such). Using the module pattern also gives you the ability to have completely private functions that only the functions within your Search object can access. (Just declare the functions within the big anonymous function and don't add them to pubs.) More on my rationale for that (with advantages and disadvantages, and why you can't combine the function declaration and property assignment) here.
Retrieving Parameters
One of the functions I really, really like from Prototype is the Form#serialize function, which walks through the form elements and builds a plain object with a property for each field based on the field's name. (Prototype's current – 1.6.1 – implementation has an issue where it doesn't preserve the order of the fields, but it's surprising how rarely that's a problem.) It sounds like you would be well-served by such a thing and they're not hard to build; then your business logic is dealing with objects with properties named according to what they're related to, and has no knowledge of the actual form itself.
Returning Values / Mixing UI and Logic
I tend to think of applications as objects and the connections and interactions between them. So I tend to create:
Objects representing the business model and such, irrespective of interface (although, of course, the business model is almost certainly partially driven by the interface). Those objects are defined in one place, but used both client- and server-side (yes, I use JavaScript server-side), and designed with serialization (via JSON, in my case) in mind so I can send them back and forth easily.
Objects server-side that know how to use those to update the underlying store (since I tend to work on projects with an underlying store), and
Objects client-side that know how to use that information to render to the UI.
(I know, hardly original!) I try to keep the store and rendering objects generic so they mostly work by looking at the public properties of the business objects (which is pretty much all of the properties; I don't use the patterns like Crockford's that let you really hide data, I find them too expensive). Pragmatism means sometimes the store or rendering objects just have to know what they're dealing with, specifically, but I do try to keep things generic where I can.
I started out using the module pattern, but then started doing everything in jQuery plugins. The plugins allow to pass page specific options.
Using jQuery would also let you rethink the way you identify your search terms and find their values. You might consider adding a class to every input, and use that class to avoid specifically naming each input.
Javascript is ridiculously flexible which means that your design is especially important as you can do things in many different ways. This is what probably makes Javascript feel less like lending itself to re-usability.
There are a few different notations for declaring your objects (functions/classes) and then namespacing them. It's important to understand these differences. As mentioned in a comment on here 'namespacing is a breeze' - and is a good place to start.
I wouldn't be able to go far enough in this reply and would only be paraphrasing, so I recommend buying these books:
Pro JavaScript Design Patterns
Pro Javascript techniques

Categories