Difference of time between server and database in Grails 4.0.3 - date

I developed a Grails 4.0.3 Rest API to send notifications the to users of a system.
When I save a message in the database, I don't know why but it adds three hours from the current Date. First of all I thought that it was the hour of te server, but when I saw it, I noticed the hour of the server is correct.
Now in Brazil the time is 2022-08-16 12:08:54.710 and the server is correct. But in the database, it saves 2022-08-16 14:55:54.710.
The code below saves a message:
def message = new Message(userId: springSecurityService?.principal?.id,
author: jsonObject.get('author'),
partId: params.partId,
title: jsonObject.get('title'),
text: jsonObject.get('text'),
createdOn: new Date()).save(flush: true, failOnError: true)
Could anyone help me with this problem?
Thanks.

I resolved the problem this way in BootStrap.groovy
System.setProperty("user.timezone", "GMT-03")
TimeZone.setDefault(TimeZone.getTimeZone("America/Sao_Paulo"))

Related

Facebook Conversions API - Invalid Timestamp errors

I am receiving a handful of errors regarding the event timestamp. I have confirmed that I am sending a UNIX timestamp in seconds. This is what I have implemented in the front-end of our code to get the UNIX timestamp in seconds: Math.round(Date.now() / 1000)
Also, it looks like less then 1% of the events are affected for each event created, so that's why I'm a bit confused and not sure how to resolve these errors.
Error message:
The timestamp for the InitiateCheckout events sent from your server is in the future. Timestamps are metadata sent alongside each event you send from your server and they represent the time of day when an event actually occurred. For example: the time that a customer made a purchase on your website. All timestamps should represent a point in time that occurred within the last 7 days"
Click here to see a screenshot of the errors
Has anyone encountered these type of errors? If so, any advice on how to resolve them?
I am not sure how to go about this

MongoError: cannot do queries on admin in atlas

I just set up a free MongoDB on Atlas. I added a database called 'react-project' that I'm trying to connect to using mongoose. Here is my connection string:
mongoose.connect('mongodb+srv://myUser:myPassword#myCluster.mongodb.net/react-project');
As you can see, at the end of the query I specify the database I want to connect to. I can connect to the mongodb instance just fine, but when I try and do an operation (such as Model.find()), I get the following MongoError:
MongoError: cannot do raw queries on admin in atlas
This leads me to believe that it is not connecting to the 'react-project' database, but is connecting to the 'admin' database instead.
Why is this happening and how can I connect to the correct database?
Here is the code I'm running that is giving me the error:
var productSchema = mongoose.Schema({
productId: Number,
img: String,
price: Number,
title: String,
type: String
});
var Product = mongoose.model('Product', productSchema);
// Return all products
Product.find(function(error,result) {
if (error) return console.error(error);
console.log(result);
});
I had the exact same issue. Seems like its a new one.
Heres my connection string that now works
mongoose.connect('mongodb://USERNAME:PASSWORD#myShard-shard-00-00-lbofd.mongodb.net:27017,myShard-shard-00-01-lbofd.mongodb.net:27017,myShard-shard-00-02-lbofd.mongodb.net:27017/MYDBNAME?ssl=true&replicaSet=myShard-shard-0&authSource=admin');
To create a new DB I used MongoDB Compass. Copy the connection string from the Atlas site(the longer one - 3.4 I believe), when you open mongodb compass it will recognize that there is a connection string in your clipboard (OSX) and will allow you to populate the connection for Compass with a simple click. You can create a new Database from there (Click on MyCluster at top left - then Create Database. Put the name of the new db in the bolded MYDBNAME in my connection string.
It did take a few refreshes to see new data.
I had much the same connection string as you (db name/shard different etc) - I was able to POST but not GET. POSTS didnt create error (but I could not find data I posted) and GET threw the same error as you got.
I just got this error after trying to switch from my paid Mongo Atlas cluster back to my free cluster. The solution for me ended up being blissfully simple:
In the URI, I changed /admin to the name of the free cluster's db or /test in my case.
String before fix:
"mongoURI": "mongodb+srv://<username>:<password>#cluster0-azhuz.mongodb.net/admin?retryWrites=true&w=majority"
String after fix:
"mongoURI": "mongodb+srv://<username>:<password>#cluster0-azhuz.mongodb.net/test?retryWrites=true&w=majority"
Had the same issue, none of the above helped. Documenting my solution since this page is the first hit on Google.
If you're using the connect-mongo library like I was, you can fix it by using the older connection string (Node 2.2 not Node 3.0). To get that in Atlas, Click on your cluster -> Connect -> Connect Your Application -> under driver choose node v. 2.2 and copy that connection string.
This is because connect-mongo can't handle the "+srv" in the newer strings.
So that string should look like
mongodb://<user>:<password>#cluster0-shard-00-00-rnmsm.mongodb.net:27017,cluster0-shard-00-01-rnmsm.mongodb.net:27017,cluster0-shard-00-02-rnmsm.mongodb.net:27017/test?ssl=true&replicaSet=cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
Got the same issue.
Changing connection string to 3.4 version (the longer one instead of 3.6) helped.
Strange, it had worked well on it on 3.6 before the issue appeared.
I have faced the same problem. Just change the /admin to your Cluster name in MongoURL.
Example:
mongodb+srv://UserName:Password#cluster0-qkaef.mongodb.net/ClusterName?retryWrites=true&w=majority
I ran into this issue using the Serverless Framework and AWS Lambda. My issue was that the environment variables were not being updated with my deploy command and it was using an older version of my Atlas connection string with an out-dated user with incorrect permissions.
So while that was a specific occurrence of my error, for other users that run into this, it seems like it could also just be a permissions issue with the user.
I found a very simple solution on a different website, but decided to share it here!
Basically, substitute /admin in the connection string to the name of your cluster in MongoDB Atlas.
Make sure you following this step. (my node version v10.15.0, mongodb compass Version 1.16.3 (1.16.3))
Make Sure your user have right readWriteAnyDatabase#admin
then copy
mongodb+srv://<yourUsername>:<yourPassword>#devconnector-xszss.mongodb.net/admin
after you copy when open mongoDB Compass will display the alert prop like this then click connect button
after login create the new database. In this case my database that I already create is name devconnector.
then in your app (in this case my app is using Nodejs) and make sure that in the url mongodb+srv://<yourUsername>:<yourPassword>#devconnector-xszss.mongodb.net/YourdatabseYouJustCreate in my case the database that I just created is devconnector. make sure it is not admin
then you can make a post request. (my post request code). my UserSchema
I hope this will help you.
I know it's really late to answer this but I was having the same problem and I just put Mongodb user name after a '/' now my connection string looks like mongodb+srv://UddeshRW:uddesh#cluster0-2erky.mongodb.net/<Mongodb user name>
I noticed you're using mongoose. Banged my head against the wall for an hour, until I rechecked the mongoose docs.
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
the .connect() method has a second parameter to specify to use the new url parser for mongo :)
Hope this helps someone (or my future self)!
Your connection URL can be any of the two:
1.
mongodb+srv://<username>:<pasword>#<your replica set>.mongodb.net/<your database name>?retryWrites=true&w=majority
mongodb+srv://<username>:<pasword>#<your replica set>.mongodb.net/<your database name>?authSource=admin&replicaSet=portal-shard-0&readPreference=primary&ssl=true
your replical set will be there automatically,
those you need to supply to your connection string are username, password and database name
so change the admin in your URL to one of your database name
Your username and password is the username and password of the user your created under Database Access in your mongo dashboard sidebar

Structuring Firebase database for Messages with Auto ID

I have been structuring my Firebase database so that messages end up being stored sequentially. Unfortunately, firebase must have made a change because now numbers no longer sort sequencially, so I have to store data a different way and still get the messages to come out in the correct order. The mainstream way to do this is to store a the message data by Auto ID. I do not understand how to properly retrieve the data though to get it back in the correct order. I have read a lot of code and docs and still that question lingers.
So, to clarify: This is what a message in my Database would look like:
id123
NAME: John
MESSAGE: Hi guys!
DATE: 11/11/16
TIME: 6:04 PM
I stored the id in that format ("id"+numberOfPost). It is considered good practice to store by Auto ID, but I do not know how to retrieve the data in its proper order. Ex. of my Database structure with Auto ID.
Kr7r2kupqerhrepqbuixd
NAME: John
MESSAGE: Hi guys!
DATE: 11/11/16
TIME: 6:04 PM
This would sort to be in the "K" section, and the post after it could start with a "B", making the database out of order. How do I structure the database to use Auto ID and yet be able to get messages in the proper order?
My code for posting a message looks like this:
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("MESSAGE").setValue(message!)
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("FIRST_NAME").setValue(fn!)
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("LAST_NAME").setValue(ln!)
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("ID").setValue(id!)
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("DATE").setValue(date!)
self.firebase.child("Chats").child(chatID!).child("id\(counter)").child("TIME").setValue(time!)
Thank you for your help!

Time offset value of a datetime is missing in Azure Web API application

I have a wep api hosted in Azure which is .NET Core. It is a simple CRUD api for now. I have an interesting problem that I could not find or understand the reason.
In my api, there is a DateTime property as usual. When I post a data to api, the time offset disappears in server side.
"dateTime":"2016-08-29T05:13:21.931+03:00" the +03:00 turns into 00:00
Can anyone explain the reason and the solution?
{
"content":"Test Data",
"location":{
"name":"Some Location",
"address":"",
"latitude":41.0920448,
"longitude":28.9444847
},
"owner":{
"userName":"Some User",
"name":null,
"registrationType":0,
"profilePictureURL":null
},
"dateTime":"2016-08-29T05:13:21.931+03:00",
"createTime":"2016-08-29T05:13:21.7791051+00:00",
"rankingPoint":0.0
}
1.First of all your azure service is runnig on 00:00 Timezone.
if you look at DateTime structure it has special property called Kind. During serialization/deserialization this property take into consideration.
DateTime dt = DateTime.Now;
// dt.Kind ( Local , Utc etc).
The way serialization works it look this property at server side Json Serialziation setting.
This option is also no help.
3. Simple and Best Solution I found is to use DateTimeOffset instead of DateTime.

saving a clientside date as UTC date object into Mongo

I am trying to save a date into meteor mongodb my challenge is as follows:
1) if i use new Date() it creates a date object in mongo DB however it saves the time as local time as javascript Date() this always comes with a timezone +0x:hours based on browser local timezone. When i retrieve this it causes havoc as i am assuming everything in my db is UTC.
2) I want to use moment js library which is great because it can represent dates in UTC properly but my challenge is how do i get mongo db to accept a moment time? The minute i use moment.format() it saves it as a string!
So how can i send a date to a mongodb insert command with a date object that is in UTC? string just dont work :(
Any help would be appreciated.
Thanks
I think everything you need to know about both of these questions can be found here and here.
TLDR:
If you directly insert/update from the client you will store a timestamp based on the user's clock. It will still be stored as UTC, but you may or may not want to trust that the time is correct. I strongly suggest using a method for any db modifications which involve time so that the server's version of time will always be used.
Moment objects are not serializable to a format compatible with mongodb. Use a date object and format it on the client.
The problem with saving dates on the client is that each client can have a different time zone, or even wrong time set. Thus the only solution is to have the date set on the server. Using a method for each insert / update is not an elegant solution.
A common practice is to modify the document inside allow or deny callback:
Messages.allow({
insert: function(userId, doc) {
...
doc.timestamp = new Date();
return true;
},
});
That way you ensure all documents have a compatible timestamp, and you can use usual db methods on the client.
The Meteor community recently started an extensive document about how to use dates and times. You'll find a lot of useful information there, in addition to David Weldon's links:
https://meteor.hackpad.com/Meteor-Cookbook-Using-Dates-and-Times-qSQCGFc06gH
However, in particular I recommend using https://github.com/mizzao/meteor-timesync when security is not a concern. It allows you to client-locally obtain an accurate server time even if the client's clock is way off, without a round-trip to the server. This can be useful for all kinds of reasons - in my apps, I universally just use server-relative time and don't care about what the client's time is at all.