Bookshelf.js save one to many relation - bookshelf.js

I am trying to save a one to many relation
My models are
Foo
foo = bookshelf.Model.extend({
tableName: 'foo',
bar: function () {
return this.hasMany('bar', 'barId');
}
Bar
bar = bookshelf.Model.extend({
tableName: 'bar',
foo: function () {
return this.belongsTo('foo', 'barId');
}
What I am trying to do
var Foo = { id: 7 }
new Bar({ blah: blah.val })
.foo()
.attach(foo);
The error I am getting
(intermediate value).foo().attach is not a function
Any help will be appreciated.

I don't think you can save data like that. I assume that the table bar has foo_id column, so all you need to do is
new Bar().save({ blah: blah.val, foo_id: Foo.id}).then(function(){});

Related

VUE 3 TS2345 when pushing an Array into another Array

as the summary mentions, i want to push a new array(Category) into another array(categoryLists)
in an exercise using vue 3 composition api, though i found something that works, i wish to try out using composables into my code
this is the declaration
const categoryLists = ref([{
id: Date.now(),
label: 'Default',
}]);
found this to be working
function addNewCategory() {
if (newCategoryName.value === '') {
console.log('no title, not added');
} else {
categoryLists.value.push({
id: Date.now(),
label: newCategoryName.value,
});
console.log(categoryLists.value);
newCategoryName.value = '';
}
}
but when i tried to use composables for this function, i instead get an error ts2345 saying that the below is un assignable to categoryLists
categoryLists.value.push(NewCategory(Date.now(), newCategoryName.value));
console.log(categoryLists);
newCategoryName.value = '';
below is the composable .ts file code
export default function NewCategory(
identifier: number,
value: string,
) {
// const Category = [identifier, value];
const Category = ref([{
id: identifier,
label: value,
}]);
console.log(Category);
return Category;
}
originally, my values are using refs, so i tried to change them to reactives but i still face the same issue
also tried not having Category as a ref
const Category = [identifier, value];
but this still shows the same issue
Argument of type 'Ref<{ id: number; label: string; }[]>' is not assignable to parameter of type '{ id: number; label: string; }'.
Type 'Ref<{ id: number; label: string; }[]>' is missing the following properties from type '{ id: number; label: string; }': id, label
can anyone show a solution or possibly explain why this isnt working

Is it possible to detect missing Object.freeze() with Flow?

Flow has $ReadOnly utility type [1] that represents a read-only view of T. Unfortunately, as Flow allows to assign a mutable T to its read-only version, it cannot be used to model the usage of Object.freeze(). In particular, it cannot detect missing calls to the latter. For example, given
type Foo = { field: string };
// frozen is assumed to be immutable with no way to change it
type WithFrozenFoo = { +frozen: $ReadOnly<Foo> }
Flow type-checks the following code:
let foo = { field: "test" };
foo.field = "new value";
let bar = { frozen: foo };
...
foo.field = "changed"; // Also changes bar.frozen.field
when the correct code should be:
let foo = { field: "test" };
foo.field = "new value";
let bar = { frozen: Object.freeze(foo) };
...
foo = { ...foo, field: "changed" }
Ideally Flow should have provided a separated $Frozen which instances can only be assigned from T via Object.freeze().
But given the lack of this, is it possible to model it in a different way even if this would involve a utility function that uses any internally?
[1] - https://flow.org/en/docs/types/utilities/#toc-readonly
It turned out just by using read-only fields we can solve the problem which also made frozen unnecessary. The drawback is cloning objects on updates, but as Object.freeze() can be slower then object creation [1], this was a useful compromise.
type Foo = { +field: string };
let foo: Foo = { field: "test" };
foo = {...foo, field: "new value"};
let bar = { frozen: foo };
...
// Now flow complain
foo.field = "changed";
[1] - https://jsitor.com/jwRCuqLFN

How to flowtype cover this code in a function with dereferenced object fields

I'm new to flow, any trying to cover some of my functions, however often I have these snippets where I extract fields form an object based on some condition. But I'm struggling to cover them with flow.
const _join = function ( that: Array<Object>, by: string, index: number) {
that.forEach((thatOBJ: {[string]: any}, i: number)=>{
let obj: {[string]: any} = {};
for (let field: string in thatOBJ) {
if (field !== by) {
obj[`${index.toString()}_${field}`] = thatOBJ[field]; // NOT COVERED
} else {
obj[field] = thatOBJ[field]; // NOT COVERED
}
that[i] = obj;
}
});
}
The array that in this code is a data array so can really be in any format of mongodb data.
Any ideas on what to add to make the two lines which are not covered by flow covered?
Thanks.
A few notes...
This function has a "side effect" since you're mutating that rather than using a transformation and returning a new object.
Array<Object> is an Array of any, bounded by {}. There are no other guarantees.
If you care about modeling this functionality and statically typing them, you need to use unions (or |) to enumerate all the value possibilities.
It's not currently possible to model computed map keys in flow.
This is how I'd re-write your join function:
// #flow
function createIndexObject<T>(obj: { [string]: T }, by: string, index: number): { [string]: T } {
return Object.keys(obj).reduce((newObj, key) => {
if (key !== by) {
newObj[`${index}_${key}`] = newObj[key]
} else {
newObj[key] = obj[key]
}
return newObj
}, {})
}
// NO ERROR
const test1: { [string]: string | number } = createIndexObject({ foo: '', bar: 3 }, 'foo', 1)
// ERROR
const test2: { [string]: string | boolean } = createIndexObject({ foo: '', bar: 3 }, 'foo', 1)

Meteor collection2 type Object

I'm trying to create a field modifiedBy with type: Object (to Meteor users).
I see you can setup blackbox: true for a Custom Object, but if I want to setup to a specific Object say a Group (collection) field modifiedBy is the logged in user, any pointers/help is greatly appreciated.
Thanks
As far as I see it, you have two options:
Store user-ids there with type: String
Denormalize it as you proposed
Denormalize it as you proposed
To denormalize it you can do something like this inside your schema:
...
modifiedBy: {
type: object
}
'modifiedBy._id': {
type: String,
autoValue: function () {
return Meteor.userId()
}
}
'modifiedBy.username': {
type: String,
autoValue: function () {
return Meteor.user().username
}
}
...
As you pointed out, you'd want to update these properties when they change:
server-side
Meteor.users.find().observe({
changed: function (newDoc) {
var updateThese = SomeCollection.find({'modifiedBy.username': {$eq: newDoc._id}})
updateThese.forEach () {
SomeCollection.update(updateThis._id, {$set: {name: newDoc.profile.name}})
}
}
})
Store user-ids there with type: String
I'd recommend storing user-ids. It's cleaner but it doesn't perform as well as the other solution. Here's how you could do that:
...
modifiedBy: {
type: String
}
...
You could also easily write a Custom Validator for this. Now retrieving the Users is a bit more complicated. You could use a transform function to get the user objects.
SomeCollection = new Mongo.Collection('SomeCollection', {
transform: function (doc) {
doc.modifiedBy = Meteor.users.findOne(doc.modifiedBy)
return doc
}
})
But there's a catch: "Transforms are not applied for the callbacks of observeChanges or to cursors returned from publish functions."
This means that to retrieve the doc reactively you'll have to write an abstraction:
getSome = (function getSomeClosure (query) {
var allDep = new Tacker.Dependency
var allChanged = allDep.changed.bind(allDep)
SomeCollection.find(query).observe({
added: allChanged,
changed: allChanged,
removed: allChanged
})
return function getSome () {
allDep.depend()
return SomeCollection.find(query).fetch()
}
})

how to use highcharts in asp.net MVC 4

I'm new in highcharts. I try to use it in my asp.net MVC 4 project. I want to pass information relative to charts from controller to view. I've used session to pass differents categories, the chart appear but without categories. Is there any solution to pass information from controller to view?
this is part of my code:
view:
<script type="text/javascript">
$(function () {
$('#divStat').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: ''
},
xAxis: {
categories: '#Session["affiche"]',
title: {
text: null
}
},
[...]
});
</script>
controller:
public ActionResult Stat()
{
String[] list = new String[5];
list[0] = "Africa";
list[1] = "America";
list[2] = "Asia";
list[3] = "Europe";
list[4] = "Oceania";
Session["affiche"] = list;
return PartialView("Charts");
}
You have to put "," among the strings to make javascript understand that is an array
#{
string[] theList = (string[])Session["affiche"];
string javascriptArrayString = "";
foreach(string str in theList){
javascriptArrayString += "'"+ str +"',";
}
javascriptArrayString = javascriptArrayString.Substring(javascriptArrayString.Length,javascriptArrayString.Length-1);
}
then:
categories: [#javascriptArrayString],
and the html result will be like :
categories: ['Africa','Asia','America','Europe','Oceania'],
this is a bit rough coding , but i think you'll get the point.

Resources