I have a problem and I want someone to help me.
My English is not that good, I'm sorry about that I'll try my best to explain the problem to you hopefully u can help me and thank you.
I'm working on an activity management platform where an employee login to his account and chose a project, then a table contains the days of a certain month under each day there is an input where he enters 1 or 0 if he worked that day or not this is how the UI looks:
When he clicks the button VALIDER (Validate in French) the data entered should be saved in mysql database.
to collect the data I used FormBuilder in angling, I defined as a form group that contains a form control that should get the name of the project, a form control that gets the month, and one for the year, and a form array that should get the values of the 3 inputs, when I console.log the value of the form I get this:
when I try to save the data in my database, I get the message successful, but when I look at my database nothing gets stored,
my database contain a table with :
projectName: varchar(45),
month: number,
year: number,
days: JSON
I think that the problem is that days are an array and not of type Jason because I tried saving an array, but I did like this: insert into project (projectName, days) values ('nomProjet', '['0', '0', '0']') and it gets saved but my days Array doesn't.
my node js code for the backend :
app.post('/cra/add', function (req, res) {
let nomProjet = req.body.projet;
let year = req.body.year;
let month = req.body.month;
let days = req.body.days;
if (nomProjet && year && month && days) {
connection.query('INSERT INTO projetcra2 ( nomProjet, month, year, days ) SET ( ? , ? , ? , ?) ',
[nomProjet, month, year, days],
function (error, results, fields) {
res.send({ status: 'success' , days});
res.end();
});
} else {
res.send({ status: 'failed', message: 'some data are required', loggedin: false });
res.end();
}
});
my formbuilder :
my save function to save to the database :
addDaysWorked() {
this.api.cra(this.form.value).subscribe(
(data: any) => {
console.log(data);
}, (error: HttpErrorResponse) => {
console.log(error);
}
)
}
when i test with postman :
my database :
I hope my problem is explained, if u think I can help with anything else let me know and thank you.
I'm not an expert at backend stuff by any means. However, I believe storing items as an array is inside of a single column in a database is not ideal. You should consider creating a new, separate table, for just days worked.
In the table, you could have a column that specified the date, whether or not he/she worked, and link obviously link this using a foreign key (like userId) to the users table or the main table in this case.
This would allow you to more easily insert the data. Since each day would just be a simple row, querying would also be simpler as you would just query data given a Timeframe (example: from beginning of August - End of August), a user (unique user ID).
Here are a couple other generic stack questions that might clarify as well.
Hope this helps!
Check out this resource as well
Related
I have an array like:
let dataArray=["abc","xyz","pqr", ...........]
let's say the size of the dataArray is 10000.
Now I want to save each data in the array as a post in the database.
Here is the code:
for (let i = 0; i < dataArray.length; i++) {
const post = new Post({
title: dataArray[i],
});
post
.save()
.then((result) => {
console.log('Post has been saved: ');
})
.catch((err) => {
console.log(err);
});
}
When the above code is executed I could see all the data of the array appear in the database but in a different order.
For example:
According to the array, abc should appear first then xyz and then pqr but when I view the database I see a post with the title xyz appear first then abc then pqr [the order shown is just for explanation purpose every time I see a random order].
Please guide me on why data appear out of order and how it could be resolved. Also let me know if more information is required.
If you are using MongoDB I think it keeps the order of the inserted elements, but it is better to add a field like createdAt to store the insertion date and you can use it later for sorting the data.
I'm running a query-builder that updates multiple users based on last logged in date, meaning I don't know which users are getting updated. Here is my code, which does not provide information about which users it updated.
await getConnection()
.createQueryBuilder()
.update(User)
.set({
isDeactivated: true
})
.where('lastConnected < :someTimeAgo', { someTimeAgo })
.andWhere('isDeactivated = :isDeactivated', { isDeactivated: false })
.execute()
.then(result => {
// Result: UpdateResult { generatedMaps: [], raw: undefined }
})
How can I access the updated data? Database is SQL Server.
Normally you cannot find which rows were updated by an UPDATE statement in SQL, hence tyeorm cannot tell you.
Here are several solutions if you REALLY need to know which rows were updated.
Before go ahead, ask WHY do you need to know? Do you REALLY need to know?
If, after careful consideration, you find you need to know which rows were updated, there are several solutions:
In your code, find the users to be deleted, then delete them one at a time, logging info on each one as you go.
Create a table in the database containing the user id's to be deactivated. Populate this table first: INSERT INTO deactivatedusers (userid) SELECT userid FROM users WHERE ... then run UPDATE users SET isDeactivated = 1 WHERE userid IN SELECT userid FROM deactivatedusers then to find which users were deactivated: SELECT userid FROM deactivatedusers and finally clear deactivatedusers ready for next time, either with DELETE FROM deactivatedusers or TRUNCATE TABLE deactivatedusers
Since you are using MS SQL Server, this provides OUTPUT INTO specifically to do what you are asking (non standard SQL, so only works with this DBMS). If you decide to use this approach, you should write a stored procedure to do the update and return the updated data back to caller, then call this stored proc from typeorm.
I have three collections in my Firebase project, one contains locations that users have checked in from, and the other two are intended to hold leaderboards with the cities and suburbs with the most check ins.
However, as a bit of a newbie to NOSQL databases, I'm not quite sure how to do the queries I need to get and set the data I want.
Currently, my checkins collection has this structure:
{ Suburb:,
City:,
Leaderboard:}
The leaderboard entry is a boolean to mark if the check in has already been added to the leaderboard.
What I want to do is query for all results where leaderboard is false, count the entries for all cities, count the entries for all suburbs, then add the city and suburb data to a separate collection, then update the leaderboard boolean to indicate they've been counted.
exports.updateLeaderboard = functions.pubsub.schedule('30 * * * *').onRun(async context => {
db.collection('Bears')
.where('Leaderboard', '==', 'false')
.get()
.then(snap =>{
snap.forEach(x => {
//Count unique cities and return object SELECT cities,COUNT(*) AS `count` FROM Bears GROUP BY cities
})
})
.then(() => {
console.log({result: 'success'});
})
.catch(error => {
console.error(error);
});
})
Unfortunately, I've come to about the limit of my knowledge here and would love some help.
Firebase is meant to be a real-time platform, and most of your business logic is going to be expressed in Functions. Because the ability to query is so limited, lots of problems like this are usually solved with triggers and data denormalization.
For instance, if you want a count of all mentions of a city, then you have to maintain that count at event-time.
// On document create
await firestore()
.collection("city-count")
.doc(doc.city)
.set({
count: firebase.firestore.FieldValue.increment(1),
}, { merge: true });
Since it's a serverless platform, it's built to run a lot of very small, very fast functions like this. Firebase is very bad at doing large computations -- you can quickly run in to mb/minute and doc/minute write limits.
Edit: Here is how Firebase solved this exact problem from the perspective of a SQL trained developer https://www.youtube.com/watch?v=vKqXSZLLnHA
As clarified in this other post from the Community here, Firestore doesn't have a built-in API for counting documents via query. You will need to read the whole collection and load it to a variable and work with the data then, counting how many of them have False as values in their Leaderboard document. While doing this, you can start adding these cities and suburbs to arrays that after, will be written in the database, updating the other two collections.
The below sample code - untested - returns the values from the Database where the Leaderboard is null, increment a count and shows where you need to copy the value of the City and Suburb to the other collections. I basically changed some of the orders of your codes and changed the variables to generic ones, for better understanding, adding a comment of where to add the copy of values to other collections.
...
// Create a reference to the collection of checkin
let checkinRef = db.collection('cities');
// Create a query against the collection
let queryRef = checkinRef.where('Leaderboard', '==', false);
var count = 0;
queryRef.get().
.then(snap =>{
snap.forEach(x => {
//add the cities and suburbs to their collections here and update the counter
count++;
})
})
...
You are very close to the solution, just need now to copy the values from one collection to the others, once you have all of them that have False in leaderboard. You can get some good examples in copying documents from a Collection to another, in this other post from the Community: Cloud Functions: How to copy Firestore Collection to a new document?
Let me know if the information helped you!
I'm trying to get the count all the data for the query and as well as get the limited data (for pagination) but both the console output gives me the count.
What is that I'm doing wrong.
Pls help
const curFind = fbUser.find(find, 'firstName gender age birthday facebookId profileURL email imageUrl preferences blocked flames likes rejects location reported')
curFind.count(function(e, count) {
console.log(count);
curFind.skip(0).limit(10).hint( { $natural : 1 } ).exec(function(err, data) {
console.log(data);
});
});
If you print the curFind object before and after executing count, you will notice that the Query object's op field changes from find to count. It may or may not be a bug with mongoose, but explains why you are getting a count again. I generally don't re-use the query object - which would solve your issue too.
I have got an item in the table and update some column value and update it into the DB.
But why this Datetimeoffset column is changed auto to another time zone ?
This is an item in DB
Using javascript backend to read and update it
request.service.tables.getTable('Ticket')
.where({ id: ticketId }).read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function (result) {
if (result.length === 0) {
console.log("ticket does not exist");
response.send(statusCodes.NOT_FOUND, { message: "ticket does not exist" });
}
//Exists; update it
else {
// do update some column
//...
//...
request.service.tables.getTable('Ticket').update(result[0]);
}
I don't change the value of DatetimeOffset column, but it is changed.
How to I can ignore update it ?
Basically, DateTimeOffset values are interpreted in the server side as JavaScript Date objects, and as such they don’t have any information about offsets (in JS dates are represented as a number of milliseconds since the “Unix 0”, 1970/01/01:00:00:00 UTC). The result was that the offset was lost in translation, and that was a problem.
=> So, the date time offset column should be in the UTC format.
I have found a post about this issue:
https://blogs.msdn.microsoft.com/carlosfigueira/2013/05/13/preserving-date-time-offsets-in-azure-mobile-services/
You can see that the actual time values are equivalent, the first contain a time zone offset. You should be able to call ToLocalTime on the client to adjust the date back to local time (or whatever the equivalent is for you client platform).