How to insert an Array of Objects in Meteor WITHOUT autoform? - arrays

The example i'm goint o use here is taken from http://autoform.meteor.com/quickform
I've been using autoform for a few projects, but i need to get this same behaviour without it, how could i do an insert of an Array of objects??
So here is the Schema definition you need with autoform
items: {
type: Array,
optional: true,
minCount: 0,
maxCount: 5
},
"items.$": {
type: Object
},
"items.$.name": {
type: String
},
"items.$.quantity": {
type: Number
}
Next is the call to autoform to generete the form in the template
{{> quickForm id="demo" schema=schemaFromJSON type="method" meteormethod="demoSubmission"}}
With that in place you get a form, displaying both fields: name and quantity, plus a sign for ading more objects with those same fields, and when you actually submit the form it inserts all of your objects.
The HTML and CSS is not the problem

I'm not quite sure what you are asking. These are two ways of inserting arrays to collection:
// insert items one by one
// NOTE: Meteor doesn't allow inserting of arrays like `Items.insert(items)`
items.forEach(item => Items.insert(item));
// insert all items simultaneously by using raw mongo collection:
Items.rawCollection().insert(items);

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!

Store and parse array in model in Waterline

Using the newest version of Waterline 0.13.1-6 standalone.
The array type no longer exist in this version. So I assume the way to store arrays is now to use the JSON type.
Sample of my model Model:
attributes: {
someArray: { type: 'json' }
}
Problem: on an instance of Model, model.someArray is now a String. I should JSON.parse it each time I request one to get the values in the array. That's very not convenient and can obviously lead to errors.
Is there a built-in way in the new Waterline to make this clean (automatically parse JSON fields...)?
You are fine to use JSON as you are suggesting. No need to parse it, this is done automatically when you do your meta fetch or find. You can do
YourModel.create({someArray: [1,2,3]}).meta({fetch: true}).then( out => {
console.log(out.someArray[0]); //1;
});
I would have some other identifying attribute for finding it, like say myRef: {type: 'string'}
Then you can do
YourModel.find({myRef: 'something'}).limit(1).then( out => {
console.log(out[0].someArray[1]); //2
});

How come store.add() method does not perform mapping?

I have a nested json data, namely:
{
name: 'alex',
tel: {
personal: '347xxxx',
work: '331xxxx'
}
}
Then the following model:
Ext.define("Employer", {
extend: 'Ext.data.Model',
idProperty: 'personalTel',
fields: [...
{name: 'personalTel', mapping: 'tel.personal'}
Finally the following store:
Ext.create('Ext.data.Store',{
model: 'Employer',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'root'
}
},
data: myInitialData //an array containing json objects
As long as the data is contained in myInitialData the personalTel field is correctly set.
However, adding a new record to the store does not trigger the mapping and so I find myself with strange personalTel property, that is automatic IDs extjs puts!
ExtJS allows you to load multiple models via nesting when using a reader. It does not allow those models to be created when instantiating the model directly, which is what adding the object to the store does.
The idea is that each model is treated separately with its own store. Want to add a customer with a telephone number? Create the telephone number first, put it in its store, then create the customer with a reference to the telephone number.
This approach is a bit clumsy, though, and only works with models that really are separate entities.
An alternative approach would be to use a custom type, or simply to use the 'auto' type (which treats the data as a blob that you can do what you want with). Both approaches have their drawbacks.

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).

Resources