javascript mongoose dynamic model assignment - javascript

Ive looked related posts and couldn't quite find what I was looking for.
So I am build a backend rest api and I have certain tests I am collecting data on. The tests have their own models, and these models are associated with collections (obviously).
So I have a separate controller for each model. Now I have a "job" controller which queries data from each separate test. Now I have a separate script where I store these model objects in an JSON object. I am wondering how I can access these models properly (I am close but cant quite assign properly). Here is the block:
const testMappings = {
'aprobe':aprobe,
'status':status,
//'rxserial':rxserial,
}
Now when I try assignment as follows, where testMappings is the imported script variable:
const testMappings = activeTests.testMappings;
console.log(testMappings['aprobe']);
I get the following output:
Model {aprobe}
I would like to access the actual aprobe object. Also if anyone knows a better way of dynamically assigning these (instead of having bunch of if statements ie if(name == 'aprobe').... do something), it would be much appreciated.

You are probably looking for something like below :
const name = 'aprobe';
Object.keys(testMappings).indexOf(name) > -1 ? testMappings[name] : null
the above should give you: Model {aprobe}
So basically if the key exists in your object then you'd like to fetch the value of that key which would give you your model dynamically.

Related

Serializing Django model

I want to serialize my Sounds model for use in my game.js file. This is what I have.
views.py
def index(request):
context = {'sounds': serializers.serialize('json', Sounds.objects.all()) }
return render(request, 'index.html', context)
index.html
<button type="submit" onclick="main()">Let's Start!</button>
game.js
function main(){
var data = {{ context|safe }};
// print all objects here
}
It's not working - not sure what the issue is. Basically, when I click the button in index.html, it should go to the main function (this part works), and then set a variable data with the objects in the model so that I can use it. Also, is it possible to filter objects in data so that I have a list with only the objects with id = 1? I want to do this in game.js (not in views.py or elsewhere).
It's hard to tell what the exact problem with the serialiser is without an actual error log. If you can actually open the console that django is running in, it should display the error when it occurs. From that a better diagnostic of the issue can be made. It would be wise to do this in the future otherwise questions like this will be downvoted.
Yes, you can filter arrays in Javascript using the filter function. The function creates a new array by interating through the objects in the array that will be passed into a function, which should return true if it should exist in the new array or false it is shouldn't.
So for the example you provided, it would appear as so:
sounds = sounds.filter((sound) => { sound.id === 1; });
Note you will have to assign the new array, the original array will not change bu running the function itself.
I highly recommend you search for solutions to these problems yourself before creating threads on Slack Overflow or your reputation will quickly decrease.

Load includes on existing model

I'm trying to load includes on an existing model in sequelize. In express we pre check the models to see if they exist in the middleware.
So once we're in the actual "controller" we want to run some includes on that existing model that is passed in.
req.models.item.incude([
{model: Post, as: 'posts'}
])
Is there any way to accomplish this?
EDIT:
I know we can do something like this.
return req.models.item.getThing()
.then(function (thing) {
req.models.item.thing = thing;
return req.models.item;
});
But:
My expansions for includes are a dynamic property that come via url parameters, so they are not know ahead of time.
It I return the above you will not see the "thing" in the response. I need it nicely built as part of the original instance.
Something like a .with('thing', 'other.thing'); notation would be nice. Or in the case of sequelize .with({include: ...}); or .include([{model: ...}]);
If the variable req.models.item is already an Instance but without its other related instances ("includes"), then you could include them using something like the following code:
Item.findAll({
where: req.models.item.where(),
include: [{
model: SomeAssociateModel,
}]
})
.then(function(itemWithAssoc) {
// itemWithAssoc is an Instance for the same DB record as item, but with its associations
});
See here for some documentation. See here for a script demo'ing this.
Update: Given the instance, how do I just get the associated models?
To do this just use the automatically generated "getAssociation" getter functions, e.g.:
function find_associations_of_instance(instance) {
return instance.getDetails();
}
I've updated the script to include this as an example. For more information on these functions, see the SequelizeJS docs.

Finding model with query strings

So looking at the ember docs page here: http://emberjs.com/guides/models/finding-records/
Ember says the following:
this.store.find('person', { name: "Peter" }); // => GET to /persons?name='Peter'`
So with this logic I did something like this
return this.store.find('entry', {week: params.week_id});
But for some weird reason ember is not making a get request with something like this
/entries?week=12
instead it's not sending any requests and neither is it returning any errors.
What's wrong exactly?
I would look at the difference between the definitions for App.Person and App.Entry.
Person defines a name property; but does Entry define a week property?
Check if you have a custom adapter for either of them. It looks like Person is using DS.RESTAdapter, but Entry might not be. Check that there is not a model-specific adapter for entry, e.g. App.EntryAdapter = ...

Best way to wrap ember-data models with their controllers

I have a custom view with a render function that needs to do some calculations. Since I've put all my display logic and properties that the app does not need to save or get on to the server in an ObjectController I need to manually "wrap" my model with the controller to get some computed properties. It works, but isn't there a better/cleaner way? So current code in the view is:
...
currentPage = pages.filterBy('nr', pageNb).get('firstObject')
currentPageCntl = #cntl.get('controllers.page').set('model',currentPage)
currentPageDimensions = currentPageCntl.get('dimensions')
...
So if I understand you correctly, you have logic and data that you don't want to include in your model, even though they belong together in certain places. I'm actually working on an issue very similar to this right now. I don't know if this is the best way to do things, but the way I've been doing it is to wrap the Ember-Data model is an object that more closely represents the model that you want. For instance, here's what that might look like for you:
App.Page = DS.Model.extend
App.PageWrapper = Ember.Object.extend
page: null
dimensions: () ->
# ...
.property('page')
So for your application, don't treat the page like your model, treat the pageWrapper as your model. So change your currentPage to:
currentPage = App.PageWrapper.create
page: pages.filterBy('nr', pageNb).get('firstObject')
This way, you can add whatever logic/models you want to the wrapper class, but still keep it distinct from your page. I might be able to help you come up with something more Ember-like if you gave me some more info, but this is a perfectly valid solution.

understand Backbone set method and Model

All, I am a newbie of Backbone. and I am trying to understand the Model of Backone. Especially how to define a Model. so far, I didn't saw a clear or formal way about how to define a Model for backbone.
For example Let's see the set method in help doc .
set
model.set(attributes, [options])
Set a hash of attributes (one or many) on the model.
Say we have some code like below . I think set method actually is assign a javascript object to the Model.
window.Employee = Backbone.Model.extend({
validate:function(attrs){
for(var key in attrs){
if(attrs[key] == ''){
return key + "can not be null";
}
if(key == 'age' && isNaN(attrs.age)){
return "age is numeric";
}
}
}
});
....
var attr = {}; // I can't not sure what is {} mean.
$('#emp-form input,#emp-form select').each(function(){
var input = $(this);//using jquery select input and select. and enumerate all of them.
attr[input.attr('name')] = input.val();//I am not sure what does it means
});
if(employee.set(attr)){
Employees.create(employee);
}
....
in this example ,I didn't saw the classical way which we can see in java class or c# class to define the class fields or methods. but only see a validate function .Is there anybody who can tell me more about it to help me understand? thanks.
To define a model in Backbone you have to extend the Backbone.Model object. For example if you'll like to create a new User model you could write something like this:
var User = Backbone.Model.extend({})
You can also overwrite some model methods to fill your needs. For example you can change the urlRoot attribute to tell the model where should he fetch the data.
Backbone models contain your data in the attributes attribute. You change those attributes by using the model set method and you can read the value stored in the model using the get method. So if you had some inputs where a user can enter information, for example creating a new user with his name and email and you have a form with a text input for both of them. You could do domething like this:
var user = new User;
user.set('name', $('#name').val());
user.set('email', $('#email').val());
attributes = {
name: user.get('name'),
email: user.get('email')
};
user.save(attributes);
There are a lot of ways to re-factor this code to make it look better but it help to see how you could use those methods. You should check the Backbone documentation to explore how they work a little bit more. Hope this helps!
PD: In my example I set an attribute a time, but you could also send a hash of attributes to set more values in one call.
The model in JS is basically a wrapper for data, with CRUD and simple validation functions. To work properly you need to make server functions to work with (ajax), I think this tutorial says it all http://backbonetutorials.com/what-is-a-model/. Instead of database the model works with your application server side.
If you have custom actions (not just add/edit/remove) on your data, you can manually "set()" data, use "onchange" event and refresh your view when needed. You can even attach "onchange" events only on specific fields and make custom functions in your view to handle each special field (for validation or display).
You can define fields at initialize and defaults value, but not custom functions (ofc you can do model.customFuntion() but I don't recommend it.
In order to make it more "clasical way" you need to use the other Backbone functions http://backbonejs.org/#Collection-Underscore-Methods and Backbone.Collection.

Categories

Resources