How do I insert an ISODate into MongoDB via Postman? I have looked around but examples/queries on this subject tend to be just for ways of getting various string formats.
I have an in-house API set up on my localhost so I am querying the database (MongoDB) with Postman. Queries & entries are written in JSON so I would do this like so usually:
{ "adminModifiedId": 1, "dateCreated" : { "$date": "1557510188"}, .., .. }
or
{ "adminModifiedId": 1, "dateCreated" : new Date(), .., .. }
Of course dates within MongoDB are in this format: ISODate("2019-01-21T17:41:27.107Z") but I just can't find the right solution here. I know that Postman does allow to set global & environmental variables within the Pre-request Script section but it does seem strange that a platform so established would not have a way to format or convert into an ISODate type.
Edited in response to #Danny_Dainton
Postman body as JSON request
Pre-request Script
Erorr response
I'll leave this for a few days to see if anyone can suggest a pre-established answer (that doesn't require a pre-request script). Otherwise I will mark mine correct as the only answer that has worked for me so far.
You could use either of these methods in a Pre-request Script.
Using the moment lib, like this:
var moment = require('moment')
pm.globals.set("ISO_Date", moment())
More info about that here: https://stackoverflow.com/a/47823708/6028443
Or
Just use basic JS code like this to create the same timestamp:
pm.globals.set("ISO_Date", (new Date()).toISOString())
Once the variable is created, add {{ISO_Date}} reference to your request body.
For whatever reason other solutions didn't work for me but may for others. This one resolved my issue though so may be of use.
Pre-request Script
let t = Date.now()
pm.environment.set('t', t);
Body (sample)
{ "adminModifiedId": 1, "dateCreated" : { "$date": {{t}}}, .., .. }
Related
I would like to find and extract details from a "stringified" api call which is a field in mongo db document.
The field is like "apiData" field below (only in one long line) which contains both request Headers and a Response Body
as an embedded object - I've separated it out on lines to make it easier to read.
The keys and values are inside "escaped" quotes
a) Can I filter/find based on a selection of header and Response body information
Currently, I'm using a regex e.g. apiData : /5684830/
Is there anything better?
b) extract a selection of header and Response body information from the field string in Mongo by
using build functionality or some else in the mongodb shell v4
Currently, I am exporting the entire field and then processing it.
I was hoping there might be a better way within the mongodb shell.
e.g Example of extract fields/end result
{
"Status Code" : "200 OK"
"numFound\": "56047",
"ebook_count_i": 14,
}
Example of document
{
_id : ObjectId("0000000000000000000000000")
apiData : {
\"Request URL\": \"http://api-call-eg.org/search.json?q=1984\"
\"Request Method\": \"GET\"
\"Status Code\": \"200 OK\"
\"Response Body\" :
{
\"numFound\": \"56047\",
\"start\": \"0\",
\"docs\": [
{
\"cover_i\": \"5684830\",
\"ebook_count_i\": 14,
\"author_name\": [ \"Rand McNally\"],
}
}
}
}
Can I filter/find based on a selection of header and Response body information
Currently, I'm using a regex e.g. apiData : /5684830/
The way you use regex is the perfect solution for the way you have stored your data
extract a selection of header and Response body information from the field string in Mongo by using build functionality or some else in the mongodb shell v4
Unfortunately, you have string. So it's the only option.
But if you can store them as field:value in mongo, you can make use of beautiful aggregation framework where you can do many queries in time efficient manner.
In Postman, the dynamic variable {{$timestamp}} inserts the current Unix Time Stamp into a request. (Represented as the number of seconds since January 1, 1970)
"currentTime": "1510934784"
However, the API I am working with expects timestamps formatted as MM/DD/YYYY.
"currentDate": "11/17/2017"
How do I insert the current date (formatted as MM/DD/YYYY) into my request with Postman?
You could use moment.js with Postman to give you that timestamp format.
You can add this to the pre-request script:
const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));
Then reference {{today}} where ever you need it.
If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.
For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/
Use Pre-request script tab to write javascript to get and save the date into a variable:
const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());
and then use it in the request body as follows:
"currentDate": "{{currentDate}}"
My solution is similar to Payam's, except I am using
//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());
If you hit the "3 dots" on the folder and click "Edit"
Then set Pre-Request Scripts for the all calls, so the global variable is always available.
Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:
var dateNow = new Date();
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();
postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);
In PostMan we have ->Pre-request Script. Paste the Below snippet.
const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());
And now we are ready to use.
{
"firstName": "SANKAR",
"lastName": "B",
"email": "SANKARB#GMAIL.COM",
"creationDate": "{{todayDate}}"
}
If you are using JPA Entity classes then use the below snippet
#JsonFormat(pattern="MM/dd/yyyy")
#Column(name = "creation_date")
private Date creationDate;
enter image description here
enter image description here
I'm adding custom data to Meteor user accounts for the first time. I've been able to add custom fields without difficulty and I know they're there because I can see them in Mongol. I am publishing via a global subscription so how do I then go about reading data from individual fields? It seems the syntax is very different from that when using publish/subscribe methods.
So, I have user accounts like this (as seen in Mongol):
"_id": "#################",
"profile": {
"name": "Test User"
},
"customfields": {
"customfield1": [
"A","B","C"
]
}
}
In server/main.js I have the following
Meteor.publish(null, function() {
return Meteor.users.find(this.userId, {fields:{customfields:1}});
});
This seems to be publishing fine. But what code do I use to render the cursor as data? I've been using variations on code like this in client/main.js and having no success:
var stuff = Meteor.users.find(this.userId).fetch();
console.log(stuff.customfield1);
Any help appreciated.
MyCollection.find() returns a cursor whereas MyCollection.findOne() returns an object, i.e. a single mongodb document.
A publication must return a cursor or array of cursors. You publication is fine.
You are basically trying to make the customfields key of the user object visible on the client. (The profile key is automatically published by Meteor).
On the client, where you are doing:
var stuff = Meteor.users.find(this.userId).fetch();
You can simply use:
var stuff = Meteor.user();
or
var stuff = Meteor.users.findOne(Meteor.userId());
Then stuff.customfields will contain what you're looking for.
The second form is way too verbose for me unless you're looking for a different user than the logged in user.
Note: this.userId on the client will not be the userId of the current user, it will be undefined. That only works on the server. That may actually be the root cause of your problem. In addition, your publications must be ready() for the data to be available. This isn't true immediately after login for example.
Since customfield1 is nested in customfields, did you try stuff.customfields.customfield1?
Hopefully this question is not too long but I am trying to include as much details as possible in what I did..
I am trying to figure out how to implement logic in Meteor.publish() that takes data from the DB, changes all the values in a column and makes the updated collection available for client-side subscription.
Specifically, I have a table that stores messages between users and the recipient is identified by his userId. I would like to replace the userId with his actual phone number which should be available in the Meteor.users table.
When I looked it up online I saw suggestions to use transform but my understanding is that it's not reactive.. I then learned about map but discovered that it returns an array which breaks the Meteor.publish() method. Finally I found something that uses forEach and self.added() and self.ready() so my code currently looks like this:
Meteor.publish("myMessages", function () {
var self = this;
Messages.find({
$or: [
{ senderId: this.userId },
{ recipientId: this.userId }
]
}).forEach(function(m) {
m.recipientId = Meteor.users.findOne({ _id: m.recipientId }).username;
console.log("adding msg to collection:");
console.log(m);
self.added("Messages", m._id, m);
});
self.ready();
});
The log messages look right and when Meteor restarts it prints all the messages from the DB related to the user where the recipient is replaced correctly with the phone number. However, on the client side when I try to run Messages.findOne(msgId) (with an id I verified exists by selecting it directly in mongo shell) I get undefined back and furthermore, running Messages.find() through developer tools in the browser returns undefined as well although I expected the messages that showed up in the logs to be available..
I feel that this is a basic use case but I am not able to make this work.. any help is appreciated!
"You can transform a collection on the server side like this:"
https://stackoverflow.com/a/18344597/4023641
It worked for me.
Unfortunately, changes in users collection will not update reactively these custom fields.
I'm getting facebook data using graph api, adding fields in string and get JSON result.
Example:
https://graph.facebook.com/me?fields=music
But JSON returned contains a "paging" key and I do not I want this key.
{ "music":{
"data":[
{
"name":"",
"category":"",
"id":"",
"created_time":""
},
{
"name":"",
"category":"",
"id":"",
"created_time":""
}
],
"paging":{
"next":"https://graph.facebook.com/me?fields=music&method=GET&metadata=true&format=json&callback=___GraphExplorerAsyncCallback___&access_token=...&limit=5000&offset=5000&__after_id=..."
}}}
EDITED:
I'm using Java API (restfb.com) to get JSON.
The command in java is:
FacebookClient client = new DefaultFacebookClient("ACCESS_TOKEN_HERE");
JsonObject rMusic = client.fetchObject("ID_HERE", JsonObject.class, Parameter.with("fields", "id,name,religion,birthday,music"));
How do I avoid it or remove it?
When you have your Javascript object built from the JSON, just pay attention to the array of data: result.music.data
And forget about the paging property: result.music.paging
Remember, there's no law in coding that you have to look at every property in your scripts.
Based upon the edit to the question above, here's a new answer.
The Rest API is deprecated. You should upgrade your app to use the Graph API as this is the one being supported.
Also, if you see a property you don't like, you don't have to access it. Remember, there's no law in coding that you have to look at every property in your scripts.