Issue with update query in titanium alloy - titanium

I'm new to titanium and alloy framework. I have created the models to store some data. I am able to insert and retrieve the data. I don't know How to update the row.
As suggest I did as follows,
var userLang = Alloy.Collections.userLanguage;
var models = Alloy.createModel("userLanguage");
models.fetch({id: 1});
models.save({
languageID: langID,
languageText: lang
});
The above code s not showing any error, But when I try to select a row from the table,
var userLang = Alloy.createModel('userLanguage');
userLang.fetch({
query: {
statement: "SELECT * FROM userLanguage WHERE id = ?;",
params: [ 1 ]
}
});
alert("Updated value : "+userLang.get("languageText"));
Model
exports.definition = {
config : {
"columns": {
"id": "integer",
"languageID": "integer",
"languageText": "text"
},
"adapter": {
"type": "sql",
"collection_name": "userLanguage"
}
}
};
The selected row is not updated as expected

...I need titanium query...
I guess that you are talking about Backbone. If so then below you can see an example how to update a model.
You can find more informations here: http://docs.appcelerator.com/titanium/latest/#!/guide/Alloy_Sync_Adapters_and_Migrations
var model = Alloy.createModel("userLanguage");
model.fetch({id: 1});
model.save({
languageID: langID,
languageText: lang
});

to update a model you should first get it from the collection
var userLang = Alloy.Collections.userLanguage;
userLang.fetch();
var langModel=userLang.get({
id:1
});
then use set to modify model's properties
langModel.set({
languageText:'new value'
});
then save it
langModel.save();
You should not update the id if you put it as the primary key ...
You should fetch data before getting any model & after updating them that's it.

Related

Add a new element in each array of objects where array may have different length in mongodb

I have a following shema.
{
id:week
output:{
headerValues:[
{startDate:"0707",headers:"ID|week"},
{startDate:"0715",headers:"ID1|week1"},
{startDate:"0722",headers:"ID2|week2"}
]
}
}
I have to add a new field into headerValues array like this:
{
id:week
output:{
headerValues[
{startDate:"0707",headers:"ID|week",types:"used"},
{startDate:"0715",headers:"ID1|week1",types:"used"},
{startDate:"0722",headers:"ID2|week2",types:"used"}
]
}
}
I tried different approaches like this:
1)
db.CollectionName.find({}).forEach(function(data){
for(var i=0;i<data.output.headerValues.length;i++) {
db.CollectionName.update({
"_id": data._id, "output.headerValues.startDate":data.output.headerValues[i].startDate
},
{
"$set": {
"output.headerValues.$.types":"used"
}
},true,true
);
}
})
So, In this approach it is executing script and then failing. It is updating result with failed statement.
2)
Another approach I have followed using this link:
https://jira.mongodb.org/browse/SERVER-1243
db.collectionName.update({"_id":"week"},
{ "$set": { "output.headerValues.$[].types":"used" }
})
But it fails with error:
cannot use the part (headerValues of output.headerValues.$[].types) to
traverse the element ({headerValues: [ { startDate: "0707", headers:
"Id|week" } ]}) WriteError#src/mongo/shell/bulk_api.js:469:48
Bulk/mergeBatchResults#src/mongo/shell/bulk_api.js:836:49
Bulk/executeBatch#src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute#src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.updateOne#src/mongo/shell/crud_api.js:550:17
#(shell):1:1
I have searched with many different ways which can update different arrays object by adding new field to each object but no success. Can anybody please suggest that what am I doing wrong?
Your query is {"_id" : "week"} but in your data id field is week
So you can change {"_id" : "week"} to {"id" : "week"} and also update your mongodb latest version
db.collectionName.update({"id":"week"},
{ "$set": { "output.headerValues.$[].types":"used" }
})

SDK2: sorting custom column in a rally grid

I have a rally grid that shows defects. I want do add a column that shows the number of days a defect has been open.
I know can do that by adding a custom renderer in the column configs, but I would also like to sort on this column. Unfortunately, the renderer does not change the sorting of the column.
I think I might be able to use the convert() function on the store instead to create a new virtual column (in this case openAgeDays), but I'm not sure how to do this from the constructor--I presume I make some changes to storeConfig?
Does anyone have an example of how to use a convert function (assuming that this is the right way to do it) to add a new virtual, sortable column to a rally grid?
this.grid = this.add({
xtype: 'rallygrid',
model: model,
disableColumnMenus: false,
storeConfig: [...]
As is the answer in the duplicate, you can add a doSort to the column:
{dataIndex: 'Parent', name: 'Parent',
doSort: function(state) {
var ds = this.up('grid').getStore();
var field = this.getSortParam();
console.log('field',field);
ds.sort({
property: field,
direction: state,
sorterFn: function(v1, v2){
console.log('v1',v1);
console.log('v2',v2);
if (v1.raw.Parent) {
v1 = v1.raw.Parent.Name;
} else {
v1 = v1.data.Name;
}
if (v2.raw.Parent) {
v2 = v2.raw.Parent.Name;
} else {
v2 = v2.data.Name;
}
return v1.localeCompare(v2);
}
});
},
renderer: function(value, meta, record) {
var ret = record.raw.Parent;
if (ret) {
return ret.Name;
} else {
meta.tdCls = 'invisible';
return record.data.Name;
}
}
},

How update datatable without render all the table again?

I´m working with datatables for a meteor app.
My problem is that when some fields change all the table is rendered again, if I´m on page two on the table or I order by field, the table is rendered again and I´m back on the beginning.
My code:
Template.adminpage.rendered = function() {
$('#userData').dataTable({
"bDestroy":true,
"aaSorting": [[ 0, "desc" ]],
"bAutoWidth":false,
"bFilter": false,
"aoColumns": [
{ "bVisible": false },
null,
null,
null,
null,
null,
null,
null
],
"aaData": Template.adminpage.arrayUsersAdmin()
});
}
Array that populates the table:
Template.adminpage.arrayUsersAdmin=function() {
var adminUsers = allUserData.find({roles: 'basic'});
var arrayUserAdmin = [];
var count=0;
adminUsers.forEach(function(user) {
var idColumn = user._id;
var dateColumn=moment(user.createdAt).format("MMM Do HH:mm");
var usernameColumn=username;
var emailColumn=email;
arrayUserAdmin[count]=[
idColumn,
dateColumn,
usernameColumn,
emailColumn
];
count++;
});
return arrayUserAdmin;
}
Collection on the server:
if(Meteor.users.find({_id: this.userId}, {roles: 'admin'})){
Meteor.publish("allUserData", function () {
var self = this;
var handle = Meteor.users.find({}).observeChanges({
added: function(id, fields){
self.added("allUsersCollection", id, fields);
},
changed: function(id, fields){
self.changed("allUsersCollection", id, fields);
},
removed: function(id){
self.removed("allUsersCollection", id);
}
});
self.ready();
this.onStop(function() {
handle.stop();
});
});
}
Thanks for your time.
You can pass reactive: false as an option to find, which disables the underlying addition of a dependency, like so:
Template.adminpage.arrayUsersAdmin=function() {
var adminUsers = allUserData.find({roles: 'basic'}, reactive: false);
// Your code
return arrayUserAdmin;
}
This behaviour is documented here
Alternatively, if you would like the individual fields to update, you will have to add them in yourself. To do this, you can use allUserDate.find({roles: 'basic'}).observe. This will require you, however, to edit the HTML directly, and is quite messy. A better alternative would be to change your table structure entirely - don't use a data table, use a vanilla HTML table, and sort the data with minimongo queries.
Regardless, you can use observe like so:
allUserData.find({roles: 'basic'}).observe({
changed: function(newDocument, oldDocument) {
// Update table
}
});

Error while trying to display content from a store

I am trying to display console.log(r.get('info')) but, i am getting the output as (an empty string). What might have caused this error ?
var myst = Ext.getStore('MyStore');
var r = myst.getAt(0);
myst.on('load', function() {
r = myst.getAt(0);
console.log(r);
console.log(r.get('info'));
});
UPDATE 1
MODEL
Ext.define('MyApp.model.MyModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'info'
}
]
});
UPDATE 2
I actually get Object { phantom=true, internalId="ext-record-18", raw={...}, more...} when i print console.log(r)'and inside raw, i see info:"myname".
To display array or objects try console.dir(object).

RavenDB Patch API: updating a nested collection

I am trying to update a nested collection using the Patch API. More specifically, consider the following example - a Posts collection:
{
"Title": "Hello RavenDB",
"Category": "RavenDB",
"Content": "This is a blog about RavenDB",
"Comments": [
{
"Title": "Unrealistic",
"Content": "This example is unrealistic"
},
{
"Title": "Nice",
"Content": "This example is nice"
}
]
}
I used the Patch API and Set-based operation docs at http://ravendb.net/docs/client-api/partial-document-updates and http://ravendb.net/docs/client-api/set-based-operations as well as several stackoverflow questions as resources to do a bulk update using set operations and a static index. A requirement is to update the "Title" of a comment only when the previous value was "Nice" and if so, update it to "Bad".
The static index "NicePosts" is defined as:
Map = posts => from post in posts
where post.Comments.Any(comment => comment.Title == "Nice")
select new {post.Title, post.Category}
The bulk patch update command is:
documentStore.DatabaseCommands.UpdateByIndex("NicePosts",
new IndexQuery(),
new[] { new PatchRequest
{ Type = PatchCommandType.Modify,
Name = "Comments",
PrevVal = RavenJObject.Parse(#"{ ""Title"": ""Nice""}"),
Nested = new[]
{
new PatchRequest {Type = PatchCommandType.Set, Name = "Title", Value = new RavenJValue("Bad") },
} }, allowStale: true);
I have some questions regarding this:
1) Is my structure/syntax for the update command correct?
2) I would like the update to be performed on all the records in the collection. Hence I haven't defined the query filter in the IndexQuery Query because the "NicePosts" index already returns the appropriate set. However running this command doesn't update the collection.
3) If I set "allowStale:false" I get a "stale index" error. Before opening my document store session I instantiate the index class and Execute it to persist it to the ravenDB instance. Any ideas whats going wrong here?
Thanks,
EDIT:
Based on ayende's recommendation changed Patch command to:
documentStore.DatabaseCommands.UpdateByIndex("NicePosts",
new IndexQuery(),
new[] {
new PatchRequest {
Type = PatchCommandType.Modify,
Name = "Comments",
Position = 0,
Nested = new[] {
new PatchRequest {Type = PatchCommandType.Set, Name = "Title", Value = new RavenJValue("Bad")},
}
}
}, allowStale: false);
This can now be done using the scripted patch request:
string oldTitle = "Nice";
string newTitle = "Bad";
documentStore.DatabaseCommands.UpdateByIndex("NicePosts",
new IndexQuery(),
new ScriptedPatchRequest
{
Script = #"for (var i = 0; i < this.Comments.length; i++)
if (this.Comments[i].Title == oldTitle)
this.Comments[i].Title = newTitle;",
Values =
{
{ "oldTitle", oldTitle },
{ "newTitle", newTitle },
},
}
);
You can't use the patch command to update values based on the existing value in the array.
You need to specify the actual position.