does anyone have some bad experience with saving float via executeRaw batch operation? Or at least an idea of how to solve my problem: ExecuteRaw is saving numbers like 7.76e-322. Input is 157 and saved value is 7.76e-322.
const items = [{uniqueId: 1, price: 100},{uniqueId: 2, price: 200}];
const completeKeys: string[] = Object.keys(items[0]);
const updateFieldsMapper = (item: any) => {
return Prisma.sql`(${Prisma.join(
completeKeys.map((key: string) => item[key])
)})`;
};
const insertKeys = completeKeys.map((key) =>
key.toLocaleLowerCase() !== key ? `"${key}"` : `${key}`
);
let insertValues = completeKeys.map((item) => updateFieldsMapper(item));
const updateSet = completeKeys.reduce((updateSet: string[], key: string) => {
if (!ingnoredKeys.includes(key)) {
updateSet.push(`"${key}" = EXCLUDED."${key}"`);
}
return updateSet;
}, []);
try {
await prisma.$executeRaw`
INSERT INTO "Product" (${Prisma.raw(insertKeys.join(","))})
VALUES ${Prisma.join(insertValues)}
ON CONFLICT (uniqueId)
DO UPDATE SET ${Prisma.raw(updateSet.join(","))};`;
} catch (error) {
console.error(util.inspect(error, false, null, true));
Sentry.captureException(error);
}
Thank you very much
Related
I want to send dynamic query to the mongoose find() method. For each iteration I need to send dynamic key and value in find method. Can someone help in this and I have tried below.
The query for each iteration needs to be find({ idle_screen : value}), find({verify_address : value})
const relatedDoc: any = {
idle_screen:1,
verify_address: 2,
update_address :3
};
Object.entries(relatedDoc).forEach(async ([key, value]) => {
// Here i want to add key as property in object
const query = { key : value} // actual o/p = {key : 1} , expected o/p = {idle_screen : 1} , {verify_address : 2}
var appointmentRefDocs = await appointment.find(query);
})```
Thanks in advance.
use for of loop for async operation .
const relatedDoc: any = {
idle_screen:data.idle_screen,
verify_address: data.verify_address,
update_address :data.update_address
};
for (const [key, value] of Object.entries(relatedDoc)) {
const query = {[key] : value}
var appointmentRefDocs = await appointment.find(query);
}
Here is the updated answer :
const relatedDoc: any = {
idle_screen:1,
verify_address: 2,
update_address :3
};
Object.entries(relatedDoc).forEach(async ([key, value]) => {
const query = { [key] : value};
var appointmentRefDocs = await appointment.find(query);
})
const dynamicFindQuery = async (data: any) => {
const relatedDoc: any = {
idle_screen: data.idle_screen,
verify_address: data.verify_address,
update_address: data.update_address
};
for (const [key, value] of Object.entries(relatedDoc)) {
const query = { [key]: value }
const appointmentRefDocs = await appointment.find(query);
}
}
If you use Typescript, then you can use Record<string, any> instead of any as the function parameter's type.
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?
})
I'm new to MongoDB and I found this function on the web. it's going to work for my all queries.
For settings.amount, settings.balance etc..
exports.updateUsers = function ( user_id, where, what, pass ) {
var _where = 'settings.'+where; //when I use it doesn't update
var update = {};
update[_where] = what;
user.findOneAndUpdate(
{'user_id' : user_id},
update).exec(function(e,d){
pass("ok")
})
};
Could anyone explain to me how can I call this query to update balance or amount?
Could anyone give me an example of updating something?
You can use it like this:
const { updateUsers } = require('./pathToFile.js'); // add the correct path;
// assuming you want to update the balance of a user to 69
updateUsers('some id', 'balance', 69, (result) => {
if(result === 'ok') {
// do something
} else if(result === 'bad') {
// you have an error
}
})
I would also change updateUsers to handle errors:
exports.updateUsers = function (user_id, where, what, pass) {
var _where = 'settings.' + where; //when I use it doesn't update
var update = {};
update[_where] = what;
user.findOneAndUpdate(
{ 'user_id': user_id },
update).exec(function (error, d) {
if (!error) {
pass('ok');
} else {
pass('bad')
}
})
};
I have 2 actions which are :
This is first
I insert person here :
export const InsertOrUpdate = (person) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get("/InsertWorker", {
params: {
Name: person.Name,
Surname: person.Surname,
Duty: person.Duty,
DateOfDay: person.Date.substring(0, person.Date.length - 9),
Shift: person.Shift,
WorkDayCount: person.WorkDayCount,
Equipment: person.Equipment,
Sicil: person.Sicil,
Ship: person.Ship
}
});
}
}
This is second
I call workers here :
export const getSignedWorkers = (collection) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get('/GetWorkers', {
params: {
DateOfDay: collection.Tarih,
Shift: collection.Vardiya
}
})
.then((response) => response.data)
.then(x => {
const Signed = str3.filter(x => x.Ship != "" && x.Shift != "H");
console.warn('signed', Signed);
const UnSigned = str3.filter(x => x.Ship == "" || null);
const RemoveOnHolidays = UnSigned.filter(x => x.Shift != "H");
const OnHoliday = str3.filter(x => x.Shift == "H");
const AllWorkers = {};
AllWorkers.signed = Signed;
AllWorkers.Unsigned = RemoveOnHolidays;
AllWorkers.OnHoliday = OnHoliday;
dispatch({ type: FETCH_SIGNED_WORKERS_SIGNED, payload: AllWorkers });
})
.catch((error) => {
console.warn('error', error);
})
}
}
I call this actions here :
_Insert = (person) => {
person.Ship = this.props.gemi_Sefer_No;
this.props.InsertOrUpdate(item); <------- Here I call first action
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var tarih = year + "/" + month + "/" + date;
let collection = {};
collection.Tarih = tarih;
collection.Vardiya = this.props.vardiya == 0 ? "S" : this.props.vardiya == 1 ? "A" : this.props.vardiya == 2 ? "G" : null
this.props.getSignedWorkers(collection); <--- Here I call second action
}
I try to insert workers to database then call all workers from database and use another component with redux. However, sometimes it works correctly sometimes not.
I mean , when I insert to database and call back again, insert worker works right however calling all workers come without worker which I insert last one. As I said, it works sometimes right. What should I do ?. Is that wrong to call two actions in same method ? if it is, what should I do ?
For the last few days, my cloud-function was running perfectly - every minute, the firestore would be queried for old posts and then they would be deleted, as such :
exports.hourly_job = functions.pubsub.topic('hourly-tick').onPublish((change,context) => {
const currentTime = Date.now()
const getPostsForDate = admin.firestore().collection('posts').where('timeOfDeletion', '<', currentTime)
return getPostsForDate.get().then(snapshot => {
const updates = {}
const batch = admin.firestore().batch()
snapshot.forEach((doc) => {
var key = doc.id
console.log(key)
const convos = admin.database().ref('/convoID/' + key).once('value', (snapshot) => {
if (snapshot.exists){
const convos = snapshot.val()
snapshot.forEach((child) => {
updates["conversations/" + child.key] = null
updates["messages/"+ child.key] = null
updates["convoID/"+ child.key] = null
})
}
})
updates["/convoID/"+ key] = null
updates["/reveals/" + key] = null
updates["/postDetails/" + key] = null
const postFireStoreRef = admin.firestore().collection('posts').doc(key)
const posterRef = admin.firestore().collection('posters').doc(key)
batch.delete(postFireStoreRef)
batch.delete(posterRef)
})
return Promise.all[admin.database().ref().update(updates), batch.commit()]
})
})
However, I started receiving the message :
TypeError: Cannot read property 'seconds' of null
at Function.fromProto (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/build/src/timestamp.js:91:46)
at _firestore.request.then.resp (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/build/src/write-batch.js:472:42)
EDIT: I fixed the date error by updating my firebase cloud functions, but the seconds is undefined still persists.
Basically, I just had to not return the batch update if there was nothing to be updated. That fixed the problem.