I wasn't able to populate a list of keys while joining on an other table so I was wondering if my models are correct and if what I'm trying to do is possible with Thinky, here is my code:
Group model
var Group = thinky.createModel('group', {
users: [thinky.type.string()],
place_id: thinky.type.string()
});
User model
var User = thinky.createModel('user', {
name: thinky.type.string()
});
Place model
var Place = thinky.createModel('place', {
name: thinky.type.string()
});
Place.hasMany(Group, "groups", "id", "place_id");
I'd like to fetch all the groups with user's name & place's name for a place_id
Here is what I've done:
Place.get(PLACE_ID).getJoin({groups: true}).then(function(g){console.log(g);});
How can I populate the user's name ? Using _apply ? How ?
Got the answer finally from the Thinky's owner :)
Thinky does join in a SQL way. See http://thinky.io/documentation/relations/
If a user can belong to multiple groups:
var Group = thinky.createModel('group', {
id: thinky.type.string(),
place_id: thinky.type.string()
});
var User = thinky.createModel('user', {
id: thinky.type.string()
name: thinky.type.string()
});
var Place = thinky.createModel('place', {
name: thinky.type.string()
});
Place.hasMany(Group, "groups", "id", "place_id");
Group.hasAndBelongsToMany(User, 'users', 'id', 'id');
Place.get(PLACE_ID).getJoin({groups: {users: true}}).then(function(g){
console.log(g);
})
Hope it helps.
Related
When making a find() request against Parse.com, each of the results I get back only contain the following fields: 'className' '_objCount' and 'id'.
How to get all fields ? (I have more than 3 columns in the database browser)
How to get specific fields ?
UPDATE 1
1) Screenshot of the headers of my class, named "Code"
2) Query:
var Code = Parse.Object.extend('Code');
var query = new Parse.Query(Code);
query.equalTo('codeSet', codeSet);
query.find()
.then(function(codes) {
console.log(codes);
}
3) Results:
[ { className: 'Code', _objCount: 1, id: '6cMkEQxE6A' },
{ className: 'Code', _objCount: 2, id: 'uOU7osLvOo' },
{ className: 'Code', _objCount: 3, id: 'Vks4QEpBlh' },
{ className: 'Code', _objCount: 4, id: 'dWtukZhsHZ' } ]
UPDATE 2
The code is hosted in a heroku-hosted node.js instance
Use PFObject get method. like user.get('nickname');
https://parse.com/docs/js/api/classes/Parse.Object.html
Just incase anyone comes accross this problem, I'm going to post an answer as it took me several hours to find the solution, which is to use toJSON().
Example:
var Parse = require('parse/node');
var User = Parse.Object.extend("User");
const query = new Parse.Query(User);
await query.get("object-id-here")
.then((user) => {
// The object was retrieved successfully.
console.log("The User Object", user.toJSON())
}, (error) => {
// The object was not retrieved successfully.
console.log("Error:", error)
});
I have two databases in my program. One for saving users and roles and one for the rest.
1) my model User has a reference to Roles. So I can populate roles by doing:
User.find({}).populate('local.roles').sort({ email: 1 }).exec(function (err, users) { ...
This works perfect and I can get a user and his roles.
2) When I try to do the same, but with models that have a connection to another database, I get the infamous error:
"MissingSchemaError: schema hasn't been registered for model ..."
This is the way I code my models when they use a different connection:
var mongoose = require('mongoose');
// to define another mongoose connection
var configScrwebDB = require('./../../config/scrwebDatabase.js');
var scrwebDBConnection = mongoose.createConnection(configScrwebDB.url);
var aseguradoSchema = mongoose.Schema({
nombre: { type: String },
abreviatura: { type: String },
rif: { type: String },
direccion: { type: String }
});
module.exports = scrwebDBConnection.model('Asegurado', aseguradoSchema);
3) this is what I do to 'populate' some field in my query (and the one that fails with above error):
var query = Riesgo.find({ cia: filtroObject.ciaSeleccionada });
query.populate('asegurado');
query.sort("codigo");
query.select("codigo fechaInicio estado moneda");
query.exec(function (err, riesgos) { ...
Of course this is in another 'js' file; and I do my 'require', etc., in order to import my models; etc.
As I said before, I can populate when models use 'default' mongoose connection.
Any ideas how I should correct this will be appreciated ... Am I missing some obvious thing here?
Thanks and bye ...
I had the same error. You could use:
var query = Riesgo.find({ cia: filtroObject.ciaSeleccionada });
query.populate('asegurado','fields to retrieve',User);// User need to be defined in the file as an variable that contents the User model defined.
query.sort("codigo");
query.select("codigo fechaInicio estado moneda");
Refer link
How to be sure that all of the view-s will be displayed in correct order. because of use of Ajax, first one finished will be displayed first, i want to always be displayed in right order...
_.each(view.collection.models, function (category) {
var productBlockListView = new ProductBlockListView({model: category});
productBlockListView.setElement(view.el).render();
}, this);
Use a comparator option to get a sorted collection.
var items = new Backbone.Collection([{
firstName: 'Steve',
lastName: 'Jobs'
}, {
firstName: 'Bill',
lastName: 'Gates'
}], {comparator: 'firstName'});
items.each(function(item) {
console.log('%s %s', item.get('firstName'), item.get('lastName'));
});
Documentation
Demo
Have json-data like this:
{ tournaments: [ {
tournament_id: "..."
tournament_name: "..."
events: [ {
event_id: ...
event_name: ....
param : [ {
param_a :
param_b : ..
subparan : [ {
sub_1: 1
sub_2 : 2...
So. I don't understand - how to it implement into BackBone Collection/Model style?
How to handle change sub_1? - Made Collection of Collection of Collection?
Simpliest way described in backbone tutorial:
var Events = Backbone.Collection.extend({
initialize: function(){
this.params = new Params()
}
})
var Tournaments = Backbone.Model.extend({
initialize: function(){
this.events = new Events()
}
})
var tournaments = new Tournaments()
You can continue nesting by you needs. When I was working on similar task I wrap each collection in model representing collection state and change itself in answer of collection events. This allows not to asking nested collections about its state having actual state in model.
var CollModel = Backbone.Model.extend({
defaults: {
state = ''//or list or dict or whatever
},
initialize: function(){
this.items = new Backbone.Collection();
this.items.on('all', this.setState, this)
},
setState: function(){
this.set(
'state',
this.items.reduce(function(state, item){
/*calculate state*/
}, '')
)
},
info: function(){
return this.get('state')
}
})
So you can nest collection-models with similar technic and read their state directly through instance.info() depends on how you calculate it. Your top model state will be updated from cascade updates of underneath models-collections.
I have a JSON data store used for a combobox selection which is working fine, however I wish to add a custom record to the combobox and it isn't working. Here is my code:
Note: I removed some of the code to make it easier to read.
var ds = new Ext.data.Store({
proxy: new Ext.data.ScriptTagProxy({
url: 'ajax.aspx?type=CR'
}),
reader: new Ext.data.JsonReader({
root: 'topics',
totalProperty: 'totalCount',
id: 'clientId'
}, [
{name: 'name', mapping: 'clientName'},
{name: 'address', mapping: 'clientAddress'}
])
});
// add the Other record
// create a Record constructor from a description of the fields
var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
{name: "id"},
{name: 'name'},
{name: 'address'}
]);
// create Record instance
var myNewRecord = new TopicRecord({
id: Ext.id(),
name: 'Other',
address: 'Other'
});
ds.add(myNewRecord);
ds.commitChanges();
var carrierSearch = new Ext.form.ComboBox({
// removed some code here
onSelect: function(record){
carrierSearch.setValue(record.data.name);
document.getElementById(carrierIdHidden).value=record.id;
fieldOnBlurPost(document.getElementById(id), page, true);
carrierSearch.collapse();
}
});
Any ideas on why the section under "// add the Other record" (up until ds.commitChanges();) isn't adding my custom record?
Thanks,
Domenic
First of all I would like to say O- H !!
From the ExtJS documentation for data.Store.add:
add( Ext.data.Record[] records ) : void
Add Records to the Store and fires the add event. To add Records to the store from a remote source use load({add:true}). See also recordType and insert.
I'm assuming that your ComboBox is using mode : 'remote'. I believe that you'll need to use the load method and feed it the {add:true} there.
I have never tried this but from the documention I would think you don't need to create the record Type again using Ext.data.Record.Create() since the datastore is provided a reader it should be available in the store. In fact, my guess is that the id property on the record type creates a different type of record object that does not match the store configuration, so it causes the add function to fail.
Try something like this:
var defaultData = {
name: 'Other Name'
address: 'Other Address'
};
var r = new ds.recordType(defaultData, Ext.id()); // create new record
ds.add(r);
I based this on the sample information found in the 'recordType' property of the Ext.data.Store class http://dev.sencha.com/deploy/dev/docs/?class=Ext.data.Store
When I added the record inside the data store it worked:
var ds = new Ext.data.Store({
proxy: new Ext.data.ScriptTagProxy({
url: 'ajax.aspx?type=CR&searchtype=begins'
}),
reader: new Ext.data.JsonReader({
root: 'topics',
totalProperty: 'totalCount',
id: 'clientId'
}, [
{name: 'name', mapping: 'clientName'},
{name: 'address', mapping: 'clientAddress'}
]),
listeners: {
load: function() {
// add the Other record
// create a Record constructor from a description of the fields
var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
{name: "clientId"},
{name: 'name'},
{name: 'address'}
]);
// create Record instance
var myNewRecord = new TopicRecord({
name: 'Other'
},'Other');
this.add(myNewRecord);
this.commitChanges();
}
}
});