ExtJS: Ext.data.DataReader: #realize was called with invalid remote-data - extjs

I'm receiving a "Ext.data.DataReader: #realize was called with invalid remote-data" error when I create a new record via a POST request. Although similar to the discussion at this SO conversation, my situation is slightly different:
My server returns the pk of the new record and additional information that is to be associated with the new record in the grid. My server returns the following:
{'success':true,'message':'Created Quote','data': [{'id':'610'}, {'quoteNumber':'1'}]}
Where id is the PK for the record in the mysql database. quoteNumber is a db generated value that needs to be added to the created record.
Other relevant bits:
var quoteRecord = Ext.data.Record.create([{name:'id', type:'int'},{name:'quoteNumber', type:'int'},{name:'slideID'}, {name:'speaker'},{name:'quote'}, {name:'metadataID'}, {name:'priorityID'}]);
var quoteWriter = new Ext.data.JsonWriter({ writeAllFields:false, encode:true });
var quoteReader = new Ext.data.JsonReader({id:'id', root:'data',totalProperty: 'totalitems', successProperty: 'success',messageProperty: 'message',idProperty:'id'}, quoteRecord);
I'm stumped. Anyone??
thanks
tom

[Responding with an answer instead of a comment for code formatting...]
Some indented formatting will make the difference clear. This (correct) form returns a single object with two properties:
{
'success':true,
'message':'Created Quote',
'data': [{
'id':'610',
'quoteNumber':'1'
}]
}
Your original format returned two separate objects with mismatched properties that cannot be resolved into columns:
{
'success':true,
'message':'Created Quote',
'data': [{
'id':'610'
},{
'quoteNumber':'1'
}]
}

Turns out that the response from the server should look like this:
{'success':true,'message':'Created Quote','data': [{'id':'610','quoteNumber':'1'}]}
A subtle difference, not one that I'm certain I understand.

Related

Meteor inserting into a collection schema with array elements

Hi I created a SimpleSchema for a Mongo collection which has a variable number of sub-documents called measurables. Unfortunately it's been a while since I've done this and I can't remember how to insert into this type of schema! Can someone help me out?
The schema is as follows:
const ExerciseTemplates = new Mongo.Collection('ExerciseTemplates');
const ExerciseTemplateSchema = new SimpleSchema({
name: {
type: String,
label: 'name',
},
description: {
type: String,
label: 'description',
},
createdAt: {
type: Date,
label: 'date',
},
measurables: {
type: Array,
minCount: 1,
},
'measurables.$': Object,
'measurables.$.name': String,
'measurables.$.unit': String,
});
ExerciseTemplates.attachSchema(ExerciseTemplateSchema);
The method is:
Meteor.methods({
addNewExerciseTemplate(name, description, measurables) {
ExerciseTemplates.insert({
name,
description,
createdAt: new Date(),
measurables,
});
},
});
The data sent by my form for measurables is an array of objects.
The SimpleSchema docs seem to be out of date. If I use the example they show with measurables: type: [Object] for an array of objects. I get an error that the the type can't be an array and I should set it to Array.
Any suggestions would be awesome!!
Many thanks in advance!
edit:
The measurable variable contains the following data:
[{name: weight, unit: kg}]
With the schema above I get no error at all, it is silent as if it was successful, but when I check the db via CLI I have no collections. Am I doing something really stupid? When I create a new meteor app, it creates a Mongo db for me I assume - I'm not forgetting to actually create a db or something dumb?
Turns out I was stupid. The schema I posted was correct and works exactly as intended. The problem was that I defined my schema and method in a file in my imports directory, outside both client and server directories. This methods file was imported into the file with the form that calls the method, and therefore available on the client, but not imported into the server.
I guess that the method was being called on the client as a stub so I saw the console.log firing, but the method was not being called on the server therefore not hitting the db.
Good lesson for me regarding the new recommended file structure. Always import server side code in server/main.js!!! :D
Thanks for your help, thought I was going to go mad!

Sencha Touch background syncing of store

I have a list that is bound to a store. I have a input text field (think chat like UX), and when the user clicks on a button, I do:
var newMessageData = {
text: textMessage
};
var message = Ext.create('MyApp.model.Message', newMessageData);
messagesStore.add(message); // At this point, the message shows up in my list
message.save(); // On a successful save, an identical message shows up again in this same list
How can I implement this, so the message only shows up once at first (immediately after the user types in something) and then the record itself just syncs with the server in the background.
Help is much appreciated! Thanks!
Edit:
My model definition is pretty simple with simple fields and a few converted fields + a custom idProperty:
idProperty: 'objectId',
{
name: 'objectId',
persist: false
}
You should be able to use messagesStore.sync() which:
Synchronizes the Store with its Proxy. This asks the Proxy to batch
together any new, updated and deleted records in the store, updating
the Store's internal representation of the records as each operation
completes.
http://docs.sencha.com/touch/2.4.0/#!/api/Ext.data.Store-method-sync
Okay, so what was missing was that I had to add the keys "primaryKey" to my hasMany and belongsTo relationships. In my case, I had idProperty: 'myCustomId', but that alone didn't work for associated models. I had to add primaryKey: 'myCustomId' to my hasMany and belongsTo relationships.

Loading multiple extjs comboboxes in a form

another ComboBox question.
In my table there are about 10 fields that are foreign keys, all presented with comboboxes.
How to fill all this combos in a form, without go 10 times to server to load the store of each one?
Are they stored as separate tables on the back end? If yes, then the correct way would be to load them going to the server 10 separate times. You can optimize this scenario by:
loading them all simultaneously
loading them all before you get to that page in advance
But you still would want to have 10 different stores in your ExtJs application.
If you wish to combine them into single store remember couple things
you would need to add additional field into this combined table so you can distinguish different lists.
you would load them all at once
then you would still need to separate them into different store objects because otherwise different UI components (comboboxes) won't be able to show different sets of data
Well known problem :) Typically when I have structure like this
var data = {
ForeignKeyObjectId: 123,
ForeignKeyObject: {
Id: 123,
SomeValue: 'Some text 1'
},
SomeOtherObjectId: 456,
SomeOtherObject: {
Id: 456,
SomeValue: 'Some text 2'
}
//, ... same 8 times more
}
I have to load each combo manually:
var combo1 = this.down('#foreignKeyObjectCombo');
combo1.setValue(data.ForeignKeyObject.Id);
combo1.setRawValue(data.ForeignKeyObject.SomeValue);
combo1.store.loadData([data.ForeignKeyObject], true);
var combo2 = this.down('#someOtherObjectCombo');
combo2.setValue(data.SomeOtherObject.Id);
combo2.setRawValue(data.SomeOtherObject.SomeValue);
combo2.store.loadData([data.SomeOtherObject], true);
// same 8 times more
In one of my previous projects on ExtJs 3 I made some overrides for form and combobox behaviour so that I could use form.getForm().loadData(data) once instead of manually setting value, rawValue like in this example. But that way was implicit, so I like more this way :)
Example:
Model 1
Ext.create('Ext.data.Store', {
model: 'EmployeeType',
data : [
{type: 1, description: 'Administrative'},
{type: 2, description: 'Operative'},
]
});
Model 2
Ext.create('Ext.data.Store', {
model: 'BloodType',
data : [
{type: 1, description: 'A+'},
{type: 2, description: 'B+'},
]
});
Even if your stores have Proxy, you can disable AutoLoad so you can load as many as you want in one single request like this:
Create the stores manually:
employeeType = Ext.create('Ext.data.Store', {model: EmployeeType});
bloodType = Ext.create('Ext.data.Store', {model: BloddType});
Create an Ajax request where you bring all combos at once:
Ext.ajax.request({
url: './catalogs/getalldata',
success: function(response) {
var json = Ext.decode(response.responseText);
employeeType.loadData(json.employeeTypes);
bloodType.loadData(json.bloodTypes);
//...
}
});

MongoDB: Query and retrieve objects inside embedded array?

Let's say I have the following document schema in a collection called 'users':
{
name: 'John',
items: [ {}, {}, {}, ... ]
}
The 'items' array contains objects in the following format:
{
item_id: "1234",
name: "some item"
}
Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB? I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}. But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want? I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.
The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })
You will have :
{
name: "John",
items:
[
{
item_id: "1234",
name: "some item"
}
]
}
See Documentation of $elemMatch
There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to. Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details. Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828. It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.
If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
_id: {user_id: ObjectId, item_id: "1234"},
name: "some item"
}
Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).

extjs store fail

ExtJS Model fields have mapping option.
fields: [
{name: 'brandId', mapping:'brand.id', type: 'int'},
{name: 'brandName', mapping:'brand.name', type: 'string'},
The problem is: if the response from server does not contain some field(brand field in my example) and mapping from inner fields is defined, Ext Store silently fails to load any records.
Does anybody have problems with this? Is it some kind of a bug?
UPDATE
To make it clear: suppose I have ten fields in my model. Response from server has nine fields, one is missing. If there is no nested mapping for this field (mapping:'x.y.z') everything is OK - store loads record, the field is empty. But if this field has to be loaded from some nested field and has mapping option - store fails to load ANYTHING.
UPDATE 2
I have found the code, that causes problems. The fact is: when Ext tries to load some field from Json it performs a check like this
(source["id"] === undefined) ? __field0.defaultValue : source["id"]
But when field has mapping option(mapping 'brand.id') Reader does it this way
(source.brand.id === undefined) ? __field20.defaultValue : source.brand.id
which causes error if source has no brand field.
In case you have same problems as I: you can fix it by overloading Ext.data.reader.Json's method createFieldAccessExpression
I agree that Ext should only fail to load that field, not the entire record. One option that isn't great, but should work, is instead use a mapping function:
{
name: 'brandId',
mapping: function(data, record) {
return data.brand && data.brand.id;
}
}
I could have the arguments wrong (I figured out that this feature existed by looking at the source code), so maybe put a breakpoint in there to see what's available if it doesn't work like this.
I think you're misinterpret mapping and nesting paradigms: these are not interchangeable.
If you define nesting in your data, the result MUST have the corresponding field.

Resources