I have problem with Mongo/express array parsing. A array from body seems to be correct when I console.log response in node console. But the problem is when I try to save the body to mongo.db using insert.one method, the post is saved but the array turns into string, which is bad for me.
This is what I'm sending to mongo (the data is ok, i console.log it, array is not string here)
{
createdBy: this.userName,
postContent: this.post,
tags: this.tags,
addedAt: new Date()
};
And this is what is stored in database
Update:
When I hardcode array into payload it's showed correctly as an array in mongo.
But of course problem still exist for dynamic data
You should be able to use JSON parse along with a replace to force it to accept the string as an array, like this:
const array = JSON.parse(this.tags.replace(/'/g, '"'));
Then set tags to the value of array:
tags: array
Use data type as array -- 4 and use .pretty().
Generally if you use find() method returns data in a dense format.
By using cursor.pretty() you can set the cursor to return data in a format that is easier for humans to parse
Related
I have the following code:
localStorage.setItem("ActiveDataOfpModel", iHandle.find("ul li.pModel.active"));
When i check "ActiveDataOfpModel" value in console i get "[object Object]".
How can i store the actual object in "ActiveDataOfpModel" and retrieve its properties. i.e. i want to do the following:
var value = localStorage.getItem("ActiveDataOfpModel").attr("data-id")
i did try
var value = JSON.parse(localStorage.getItem("ActiveDataOfpModel")).attr("data-id")
but its not working
You can only store strings in local storage.
You can encode simple objects as JSON (they must contain only JSON data types such as objects, numbers, and strings) as a string using JSON.stringify(someObject).
var value = JSON.parse(localStorage
… and that is how to convert the JSON back to an object afterwards.
Your code iHandle.find("ul li.pModel.active") implies you are not dealing with a simple object though. That is something I would expect to return a DOM element or something akin to it.
You would need to extract the data you care about from it, store that in an object, store that in the JSON and then the localstorage, and write more code to convert the simple data back in to the full object when you pull the data out afterwards.
Try this:
Convert it to String before saving to LocalStorage
localStorage.setItem('key', JSON.stringify(data));
Convert back to JSON object, when reading from LocalStorage
data = JSON.parse(localStorage.getItem('key');
So, I used data declared by myself, but now i switch the code to LocalStorage, and I'd like to know, how to get the data from one element of LocalStorage, and insert it to a block of data from my program.
Here's a part of code which shows the procedure which i use for inserting data
let l = this.lists;
localStorage.setItem('lists', JSON.stringify(l));
l is of type string, and lists is an array with data block.
I wanted to use this command
this.lists = localStorage.getItem('lists');
but unfortunately,it wants a string element, and doesn't want to work with my lists element...
Info time:
LocalStorage is implementation of Storage interface and it accepts and
returns plain strings so every time you want to store there something
a little bit more complex you have to serialize when inserting
(JSON.stringify) and deserialize when retrieving (JSON.parse)
You can use JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
this.lists = JSON.parse(localStorage.getItem('lists'));
localStorage is implementation of Storage interface, It works on plain strings. When you want to work with complex object serialize it using JSON.stringify() and deserialize using JSON.parse()
I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.
I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.
I have an object like this:
var queryObject= {
name: 'Shwetanka',
subjects: ['Mathematics', 'Physics', 'Computers'],
stream: 'science'
};
When I create query string with this using $.param(queryObject) I get this as query string:
name=Shwetanka&subjects%5B%5D=Mathematics&subjects%5B%5D=Physics&subjects%5B%5D=Computers&stream=science
Expected: name=Shwetanka&subjects=Mathematics&subjects=Physics&subjects=Computers&stream=science
How do avoid [] added by the method in the query string for params with same name. In the backend I'm using struts2 to read params.
I've found the solution. I just have to pass 'traditional=true' in $.param(queryObject, true). This generates the query string i want.
When we have fields with same name in a form and it is submitted via GET/POST, it is bound to be send as an array of params with the same name.
And the server would be expecting the values as such. So, Even if you somehow remove that [], it ceases to be an array, and the server will get only one value.
jQuery param method is designed, with the same thing in mind.
Check out examples in http://api.jquery.com/jQuery.param/.