How to update a record and update include many records relationship by foreignKey in sequelize use db postgres - postgresql

I create an API that updates a record associated with a foreign key
if I just put a value to items so I want it to return remove other values that I don't put
if I edit some value in items so I want it to return the value that I edited
if I put value over value of items so I want it to return the old value of items and the value that I put over
example: const record = {id:1,name:"abc",items:[{id:1,name:"abc",recordId:1},{id:2,name:"abcd",recordId:1}]}
const update = await dbRecord.update({id,name},{where: {id: req.params.id},include:[model:'items',id:[1,2]});

You can use Sequelize mixins. Sequelize has special methods that uses the prefix get add set concatenated with the model name.

const update = await dbRecord.update(
{ id, name },
{ where: { id: req.params.id } }
);
//array get from body
ex: array = [
{ id: 1, name: "abc", recordId: 1 },
{ id: 2, name: "abcd", recordId: 1 },
];
const itemId = array.map((arr) => arr.id);
// result = [1,2]
await dbItems.bulkCreate(array, {
updateOnDuplicate: ["name"],
});
for (var i = 0; i < update.items.length; i++) {
const item = update.items[i];
if (!itemId.includes(container.id)) {
await container.destroy();
}
}
so it create update delete in once time.

Related

override object properties in createAsyncThunk method

I have a function like this
export const fetchChildrenNews = createAsyncThunk('news/fetch1', async ([item, news]) => {
const res = await Promise.all(item.kids.map(id => {
let url = `https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`;
return fetch(url);
}));
const jsons = await Promise.all(res.map(r => r.json()));
let users = {...item, kids: jsons};
item.kids = []//doesn't work
item.id = 0 //doesn't work
//I want to find a branch in the original tree and replace it
const tree = (obj) => {
for (let key in obj) {
if (key === "id" && obj[key] === users.id) {
obj = users;
}
if (key == "kids") {
tree(obj);
}
}
}
tree(item);
where item is a nested object record: {by: 'nullzzz', descendants: 47, id: 28808556, kids: Array(13), score: 117}. kids property contains array of ids and in the users variable it becomes an array of records. and my goal change record.kids = [0, 7, 14] to record.kids = users ([{by: '...', id:4848,..], [{by: 'adasd'], [{by: 'zzz}] ). the variable news is a whole tree while item its branches.
I just started working with the toolkit, so I don't fully understand this
Since item is probably an object from your Redux store, that thunk would try to modify a reference to your store - and modifying the store is only allowed in reducers.
Generally, you should be doing logic like this in reducers, not in a thunk.
So, do
export const fetchChildrenNews = createAsyncThunk('news/fetch1', async ([item, news]) => {
const res = await Promise.all(item.kids.map(id => {
let url = `https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`;
return fetch(url);
}));
const jsons = await Promise.all(res.map(r => r.json()));
return jsons
})
and then in your slice, add the logic:
builder.addCase(fetchChildrenNews, (state, action) => {
const jsons = action.payload
// here, do not modify `items`, but modify `state` - I would assume `items` is somewhere in here anyways?
})

Add/Update list of K,V pair to empty declared map = List<Map<dynamic, dynamic>>

I have and empty map, Map optionSelection = {};
And on every button click I want to add list of K,V pair map to optionSelection map.
Format in which I want to add Map.
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
}
In above Key and Value pair, in "ques_id": questionId -> questionId will be unique, So I want to check if the value already exist, if YES then I want to update the "user_ans_id": selectedOption value or else I want to add new list of K,V pair.
Below is the code I tried
final quesExist = optionSelection.containsValue(questionId);
if (quesExist) {
optionSelection.putIfAbsent(
"ques_id",
() => optionSelection.addAll(
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
},
),
);
} else {
optionSelection.addAll(
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
},
);
}
Hope I was able to explain my issue, Thank you in advance.
after a week of struggle and many tweaks in code, here is the final solution for above query.
// Declared empty List<Map>
List<Map> optionSelection = [];
// Variable to store bool value, if the question id exist
var questionExist;
// Feed the map in below form
Map<String, dynamic> userSelection = {
"quiz_id": widget.quizId,
"ques_id": questionId,
"user_ans_id": selectedOption,
};
// Check if the Ques Id Exist in List<Map> optionSelection
questionExist = optionSelection.any((map) => map.containsValue(questionId));
// Check using if else condition, if Ques Id exist, then run the forLoop,
// to iterate in List<Map>, else add a new Set of Map to the List<Map>
if (questionExist == true) {
print("If triggered");
for (var map in optionSelection) {
if (map.containsValue(questionId)) {
map.update("user_ans_id", (dynamic val) => selectedOption);
}
}
} else {
print("Else triggered");
optionSelection.add(userSelection);
}

Mongo Db bulk update operation for data type conversion

How to perform bulk operation for mongo db? I already have script to change data type but it is not considering huge volume.
Collection 'store' has column called 'priceList' which is Array having multiple fields one of which is 'value'. Right now it is integer and now I want to convert it to custom record object.
Current schema
store
- _id
- name [String]
- priceList [Array]
- amount [Record] //{"unscaled":<value>, "scaled", <value>}
- value [Integer]
Need to convert value to [Record] as mentioned in above format
For e.g:- value: 2 will become value: {"unscaled":2, "scaled", 0};
db.store.find({priceList: { $exists : true}}).forEach(function(obj){
obj.priceList.forEach(function(y){
y.value = ({"unscaled":NumberLong(y.value),"scaled",NumberInt(0)});
db.store.save(obj);
})
});
Thanks!!
you try like this,
db.store.find({
priceList: {
$exists: true
}
}).forEach(function(myDoc) {
var child = myDoc.priceList;
for (var i = 0; i < child.length; i++) {
var ob = child[i];
var obj = {"unscaled":NumberLong(ob.value),"scaled":NumberInt(0)};
if ('value' in ob) {
ob.value = obj;
child[i] = ob;
}
}
db.store.update({
_id: myDoc._id
}, {
$set: {
subMenu: child
}
});
});
Hope this helps (updated) !
db.store.find({priceList: {$exists: true}})
.toArray()
.forEach(o => db.store.update(
{_id: o._id},
{ $set: {
priceList: o.priceList.map(l => Object.assign(l, {
amount: {
unscaled: l.value,
scaled: 0
}
}))
}
}
))

winJS ListView dynamic datasource edit issue

winJS ListView issue
I am working on a winJS application.I have listview.I need to add new data to an existing list view.How can i do that?
Normally the listview is bound with a WinJS.Binding.List, just add new items to that list and they'll appear inside listview.
Suggest use WinJS.Binding.List.createSorted() first and createGrouped on the sorted list. if your sort function can ensure that the newly inserted item comes ahead in sort order - it should appear first in the group.
_initializeListView: function initializeListView()
{
var data = [{ title: 'parle-ggg', brand: 'parle' }, { title: 'parle-gg', brand: 'parle' }, { title: 'parle-g', brand: 'parle' },
{ title: 'maggi-sauce', brand: 'maggi' }, { title: 'maggi-sauce-2', brand: 'maggi' }, { title: 'maggi-sauce-3', brand: 'maggi' }];
var list = new WinJS.Binding.List(data);
var sortedList = list.createSorted(function sorter(item1, item2)
{
var result;
if (item1.title < item2.title)
result = -1;
else if (item1.title == item2.title)
result = 0;
else
result = 1;
return result;
});
var groups = sortedList.createGrouped(
function groupKey(item)
{
return item.brand;
},
function groupData(item)
{
var result = { title: item.brand };
return result;
}
);
listView.winControl.itemDataSource = groups.dataSource;
listView.winControl.groupDataSource = groups.groups.dataSource;
this.sortedList = sortedList;
},
_oncmdclick: function oncmdclick(event) // this is event handler where you want to add new item
{
this.sortedList.push(newItem);
},
the above code snippet is tries to create a list sorted by title and grouped by brand. on inserting an item later in sortedList - inserted item is placed in the group properly. for example - adding an item by title 'parle-f' will place it first in the parle brand group whereas adding an item by title 'parle-h' will place it last in the parle brand group.
HTH.

in mongo need to join two collections using Identity columns and emit the needed columns from both collections

I have book and author collection.in this name and works_written are the same value column respectively.so i tried the following script but it emit only first map values,second map values not emitted.
book = function() {
emit(this.id, {name: this.name,editions:this.editions});
}
author = function() {
emit(this.id, {name:this.name,works_written: this.works_writtten,});
}
r_b = function(k, values) {
var result = {};
values.forEach(function(value) {
var name;
for (name in value) {
if (value.hasOwnProperty(name)) {
result[name] = value[name];
}
}
});
return result;
};
r_a = function(k, values) {
var result = {};
values.forEach(function(value) {
var works_written;
for (works_written in value) {
if (value.hasOwnProperty(works_written)) {
result[works_written] = value[works_written];
}
}
});
return result;
};
res = db.book.mapReduce(book, r_ja, {out: {reduce: 'joined'}})
res = db.author.mapReduce(author, r_jp, {out: {reduce: 'joined'}})
can someone help me out?
From looking at your code, it seems like you have two collections, "book" and "author". Each book is structured as
{
id: <some id>,
name: <some name>,
editions: <comma-separated string of editions>
}
and each author is structured as
{
id: <some id>,
name: <some name>,
works_written: <comma-separated string of works written>
}
It would be more reasonable to store both works_written and editions as arrays rather than comma-separated lists each packed into an individual string. This would make iterating over the array possible.
Additionally, do you have multiple documents for each author and each book? If not, you do not need a mapreduce to do what you are attempting to do - a simple find() should work.
In case I have misinterpreted, what exactly are you attempting to do?