Update column with array entry; create column if it does not exist - rethinkdb

r.table("bets").filter({id: betID}).update({
votes: r.row('votes').append({
userID: userID,
vote: vote
})
}).run(connection, function(err, result) {
// ...
});
My goal ist to update a document in the bets table with the given betID. I want to update the column votes, which might not exist. If it does not exist, I want to create the column, and append the array element afterwards. If it exists, I just want to append the array element.
result.replaced returns 1, which is correct, but the column votes is not created... any idea?

Found the solution:
var newVote = {
userID: userID,
vote: vote
};
r.table("bets").filter({id: betID}).update({
votes: r.row('votes').default([]).append(newVote)
}).run(connection, function(err, result) {
});
See. https://rethinkdb.com/api/javascript/update/

Related

How to query relational data in ascending order in strapi?

I have this query that works
async find(ctx) {
let { _start, _limit } = ctx.request.query;
console.log(ctx.request.query)
_limit ? 0 : (_limit = 10);
const entities = await strapi.services["course-series"].find({});
return entities.map((entity) => {
// Do I sort them here or in the url query (and how)
entity.courses = entity.courses.slice(_start, _limit);
return sanitizeEntity(entity, { model: strapi.models["course-series"] });
});
}
The idea is that I can load 10 courses from each series at first and then get the next 10...
I just realized that the first 10 I am getting are not the recent ones.
As I commented // Do I sort them here or in the url query (and how)
What version of Strapi do you use?
What does this line do strapi.services["course-series"].find({})? How did you build this find method in the service? What does it do? Does it accept params?
Personally I'd do something like that (assuming you're working with Strapi version > 4:
const entities = await strapi.entityService.findMany('api::course-series.course-series', {
fields: [/* list the course-series fields you want to populate */],
populate: {
courses: {
fields: [/* list the course fields you want to populate */],
sort: 'createdAt:desc', // You can use id, publishedAt or updatedAt here, depends on your sorting prefrences
offset: _start,
limit: _limit // I must admit I haven't tested `offset` and `limit` on the populated related field
}
}
})
// ...the rest of your code, if needed
Read more about Entity Service API here.
Doing it the way you did it, you will always first retrieve the full list of courses for each course-series, and then run costly operations like mapping (the lesser of 2 evils) and above all sorting.

Return custom field based on other not requested field?

Let's say that I want to get a person's age using this query:
{
getUser(id: "09d14db4-be1a-49d4-a0bd-6b46cc1ceabb") {
full_name
age
}
}
I resolve my getUser query like this (I use node.js, type-graphql and knex):
async getUser(getUserArgs: GetUserArgs, fields: UserFields[]): Promise<User> {
// Return ONLY ASKED FIELDS
const response = await knex.select(this.getKnexFields(fields)).from(USER).whereRaw('id = ?', [getUserArgs.id]);
// returns { full_name: 'John Smith' }
return response[0];
}
The problem is that then I can't calculate age field, because I did not get born_at (datetime field stored in a db) in the first place:
#FieldResolver()
age(#Root() user: User, #Info() info: GraphQLResolveInfo): number {
console.log(user); // { full_name: 'John Smith' } no born_at field - no age, so error
// calculate age from born_at
return DateTime.fromJSDate(user.born_at).diff(DateTime.fromJSDate(new Date()), ['years']).years;
}
Is there some fancy graphql-build-in way / convention to predict that born_at will be needed instead of doing it manually through info / context?
You should always return full entity data from the query-level resolvers, so they are available for field resolvers.
The other solution is to manually maintain a list of required fields for field resolvers, so your "fields to knex" layer can always include them additionally".
Further improvements might be to can a list of additional columns based on the requested fields (thus the field resolvers that will be triggered).

How to Insert value into main field in Wix Corvid

I have event table in Corvid Database, it has Event_Id column for every new event which is not asked from the user in the form.
I used the following code to get the number of rows and generate id from that which works good now:
let count = 0;
$w("#collection").onReady( () => {
count = $w("#collection").getTotalCount(); // 23
count++;
} );
$w('#btnSub').onClick( ()=>{
const newRequest = {
eventid:('event_'+count),
title: $w('#title').value
}
wixData.insert('event_instance', newRequest);
but this can lead to duplication of event id as I delete one of the row from collection
Can you please find a solution for this?
Thanks
You need to use dropdowns in #myElementID
This similar to this in SQL.
if not exists (select * from Delegates d where d.FromYr = #FromYr and d.MemNo = #MemNo)
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(#MemNo, #FromYr,#ToYr)
Else refer this
Make sense get count before each insert
$w('#collection').onReady( () => {
$w('#btnSub').onClick( () => {
const count = $w('#collection').getTotalCount() + 1; // here
wixData.insert('event_instance', {
eventid: ('event_' + count),
title: $w('#title').value
});
});
});

ExtJs 6 doSort method

I didn't find doSort function available in EXT 6 with respect to the grid columns and also didnt find it in any upgrade notes. may be because it is a private function, can anyone please tell me what is the alternative to do the same thing what doSort was doing in Ext 4 ?
I tried to use sorters instead,
{
text: 'columnText',
dataIndex: 'columnIndex',
sorter: me.sort
}
sort: function(v1,v2) {
...
}
but i didn't found smth like dataIndex or columnName in v1, v2 parameters to do sort. (it's just a model)
I need empty cell be from below after Sort Ascending, empty cell be from above after Sort Descending
Thanks.
What is the problem here? You can use the model object to retrieve your column data to sort. From the docs:
sorter: function(record1, record2) {
var name1 = record1.data.columnIndex;
var name2 = record2.data.columnIndex;
return name1 > name2 ? 1 : (name1 === name2) ? 0 : -1;
}
EDIT: If you dont want to rewrite this for every column, then you can do a trick like this:
sorter: (function(columnIndex){ return function(v1, v2){ me.sort(v1, v2, columnIndex);} })("column1")
Now, you can get the column name as 3rd argument in your sort function.
You want to sort the store, not a column. Have a look at the doSort function in ExtJS 4 for a moment:
doSort: function(state) {
var tablePanel = this.up('tablepanel'),
store = tablePanel.store;
// If the owning Panel's store is a NodeStore, this means that we are the unlocked side
// of a locked TreeGrid. We must use the TreeStore's sort method because we cannot
// reorder the NodeStore - that would break the tree.
if (tablePanel.ownerLockable && store.isNodeStore) {
store = tablePanel.ownerLockable.lockedGrid.store;
}
store.sort({
property: this.getSortParam(),
direction: state
});
},
/**
* Returns the parameter to sort upon when sorting this header. By default this returns the dataIndex and will not
* need to be overriden in most cases.
* #return {String}
*/
getSortParam: function() {
return this.dataIndex;
},
Now, this code is still working in ExtJS 6, just that it is no longer part of the framework. You can "put it back into the framework" (e.g. as an override) and it should work again. Or you can use the relevant parts directly from the column event, e.g.
columns:[{
dataIndex:'ABC',
listeners:{
headercontextmenu:function(ct, column) {
column.mySortState = column.mySortState=='ASC'?'DESC':'ASC';
ct.up('grid').getStore().sort({
property:column.dataIndex;
direction:column.mySortState
});
}
}
}]
Maybe you need to define it in the model like this:
fields: [{
name: "textField",
type: 'string',
//sortType: 'asInt'
}]

SQLite Swift db.prepare Optional() in statement values

In the SQLite Swift documentation there is reference to getting statement results directly. I have a lot of SQL queries prepared and I don't really want to refactor them. I would sooner use them as they are using db.prepare, as per below.
Statements with results may be iterated over.
let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
print("id: \(row[0]), email: \(row[1])")
// id: Optional(1), email: Optional("alice#mac.com")
}
The return values always have the "Optional()" around them. Is there a way we can just get the raw row values back without this?
Unwrap the values using ! after the variable as #stephencelis said:
let stmt = try db.prepare("SELECT id, email FROM users")
for row in stmt {
print("id: \(row[0]!), email: \(row[1]!)")
}
You may want to use https://github.com/groue/GRDB.swift. It lets you extract optionals or non-optionals, just as you wish:
for row in Row.fetch(db, "SELECT id, email FROM users") {
let id: Int64 = row.value(atIndex: 0)
let email: String = row.value(atIndex: 1)
print(id, email)
}
The type-safe API lets you declare expressions of non-optional types that, when pulled back from a statement, are not wrapped.
From the README:
let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")
try db.run(users.create { t in
t.column(id, primaryKey: true)
t.column(name)
t.column(email, unique: true)
})
// CREATE TABLE "users" (
// "id" INTEGER PRIMARY KEY NOT NULL,
// "name" TEXT,
// "email" TEXT NOT NULL UNIQUE
// )
let insert = users.insert(name <- "Alice", email <- "alice#mac.com")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice#mac.com')
for user in db.prepare(users) {
println("id: \(user[id]), name: \(user[name]), email: \(user[email])")
// id: 1, name: Optional("Alice"), email: alice#mac.com
}
Note that both id and email, which are non-optional, are returned as such.

Resources