I imagine this has been posted before but I wasn't able to find a data object specifically like this one. I'm struggling to understand how extract information from this data object in javascript. It's a parsed URL.
data = URL {
href: 'http://localhost:8080/test.txt?cat=Mouse',
origin: 'http://localhost:8080',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:8080',
hostname: 'localhost',
port: '8080',
pathname: '/test.txt',
search: '?cat=Mouse',
searchParams: URLSearchParams { 'cat' => 'Mouse' },
hash: ''
}
I can retrieve the URLsearchParams
data.searchParams, which returns { 'cat' => 'Mouse' }
What is this data structure called: { 'cat' => 'Mouse' }. I'm confused by the =>
And how do I retrieve the two objects 'cat' and 'Mouse' separately inside this data structure?
For example, retrieving then setting a variable equal to the first item, 'cat' and another variable equal to 'Mouse'
Thank you
What is this data structure called: { 'cat' => 'Mouse' }.
That isn't a data structure. It's a visual representation of the data in the URLSearchParams object.
Look at the API documentation to see how to access it (e.g. data.searchParams.entries())
There is absolutely nothing JSON related to that.
Related
I am having the following response; how can I verify its been created by having a response contains userid ?
({
id: '612bd3f42ca01806398da144',
data: Object({
createdOn: '2021-08-29T18:37:39.693Z',
lastUpdatedBy: null,
userId: '60f469cf784379051298e96d',
displayName: 'Nadia',
postText: null,
postImages: [],
pluginInstance: Object({
pluginInstanceId: '1627334094776-047554258642281355',
pluginInstanceTitle: 'communityFeedPlugin'
}),
isPublic: false,
_buildfire: Object({
index: Object({
array1: [Object({
string1: 'userId_60f469cf784379051298e96d'
}), Object({
string1: 'displayName_nadia'
}), Object({
string1: 'pluginTitle_communityfeedplugin'
}), Object({
string1: 'isPublic_0'
})]
})
})
}),
tag: 'posts'
})
If you use express rest api you can use like this.
const exists = await posts.findOne({ "data.userid": userid });
if(exists) {
return res.json({ success: false, message: "User already exists"})
}
If I get it right, you need to know if the userId property is present/truthy.
Given that the response is stored in a jsonBody variable, use an if statement like so:
if (jsonBody.data.userId) {
...
}
Also, make sure the response is parsed in JSON properly, so that you can navigate it.
If you need to know whether the response exists in the first place or not, you can add another if check:
if (jsonBody) {
...
if (jsonBody.data.userId) {...}
...
}
Or join both checks in one if statement:
if (jsonBody && jsonBody.data.userId) {...}
Anyways, it's good practice to consume backends that comunicate correctly the request status, so that you can write cleaner code avoiding this types of checks and relying on status codes for the most part.
worked in this form :
it('Add public post with post image and text', function(done) {
Posts.addPost({isPublic : true , postImages :'image test',postText : 'post text sample'},(err,resp) => {
expect(resp.data).toEqual(jasmine.objectContaining({
postImages: 'image test',
postText:'post text sample',
userId: authManager.currentUser._id,
isPublic: true
}));
done();
});
});
So, I'm trying to use the poulate and match property but without any success, I couldn't find any documentation of my problem (I struggled to find a documentation about it too, so maybe you can provide me some source other then this)?)
Btw, I have this two models:
1 - Pages
const PageSchema = new Schema({
name: String,
organization: {
type: Schema.Types.ObjectId,
ref: 'organizations',
},
})
1 - Organizations
const OrganizationSchema = new Schema({
name: String,
domains: [{
type: String,
unique: true
}],
})
I need to find the page that belongs to a specific domain, so I was doing this findOne Query:
const page = await Page.findOne({
'settings.slug': req.params.slug
}).populate({
path: 'organization',
match: {domains:"foo.com"},
}).exec()
It doesn't make the "filter" and returns the pages that have an organization without the domain "foo.com"
I tried an even more easy approach but it doesn't work neither:
const presentation = await Page.findOne({
'organization.domains': host,
'settings.slug': req.params.slug
}).populate('organization')
It returns always null.
Can someone help me? Many thanks
I think the problem is in this line
.populate({
path: 'organization', <--- you forgot an s //organizations as declared in you ref
I want to get only the json data from elasticsearch through node js.
I used
client.search({
index: 'dashboard',
type: 'test',
filterPath: 'hits.hits._source',
body: {
query: { match_all: {} }
}
})
It will show the result as:
{"_source":{"datatime":"2017-08-21 16:03:00","time_of_day":11},{"_source":{"datatime":"2017-08-21 16:03:00","time_of_day":222}]
May I know how to select only the data part in the source through node js, without "_source"? Only {"datatime":"2017-08-21 16:03:00","time_of_day":11},{"datatime":"2017-08-21 16:03:00","time_of_day":222}
Ok, solved.
can use hits.hits._source.theDataName, such as hits.hits._source.datatime , it will show "datatime":"2017-08-21 16:03:00"
I have an object that look like this:
editinvite: {
_id: '',
title: '',
codes_list: []
}
The problem is that I can't access codes_list in my NodeJS app. It shows as 'undefined' (other non-array variables work fine though)
router.post('/inviteEdit', function (req, res) {
...
console.log(req.body.codes_list);
// Output:
undefined
Note that I'm trying to use codes_list as it is, I mean I want to pass it directly to my update parameters:
var update = {
title: req.body.title,
codes_list: req.body.codes_list,
};
(extra info) Output of console.log(req.body):
{ _id: '565981a16a75a7522afdcc8b',
title: 'as',
'codes_list[0][code]': '0EHC',
'codes_list[0][_id]': '565981a16a75a7522afdcc8c',
'codes_list[0][used]': 'false',
'codes_list[1][code]': 'VDQ2',
'codes_list[1][_id]': '565981a16a75a7522afdcc8d',
'codes_list[1][used]': 'false' }
(extra info) editinvite object before sending, looks like this on FF debugger:
(extra info) My ajax call:
$.ajax({
type: 'post',
url: this.server + '/inviteEdit',
dataType: 'json',
data: this.editinvite,
crossDomain: true,
success: function (data, status, jqXHR) {
...
(extra info) I'm using these parameters in node app
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
Quoting from body-parser documentation:
bodyParser.urlencoded(options) returns middleware that only parses
urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the
request object after the middleware (i.e. req.body). This object will
contain key-value pairs, where the value can be a string or array
(when extended is false), or any type (when extended is true).
So basically if you just want string or array to be parsed you can set extended to false, for other types (like in your case array of objects) you need to set it to true.
i searched around stackoverflow and found out that cookie only can store string not array.
i have an array like this:
var myvar = {
'comment' : '123',
'blog' : 'blog',
'test' : '321
}
Then i use this jquery plugin to manage the cookies:
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
I use the below code to store the cookie named 'setting':
$.cookie('setting', myvar , { expires: 1, path: '/' });
However how do i convert that array into a string , i know i can use .join , but what if my array values for example comment , is a special character like Chinese characters etc.
and how can i access the cookie again and get the string out and convert it again into an array?
To store an object in a cookie:
var myvar = {
'comment' : '123',
'blog' : 'blog',
'test' : '321'
};
var serialized = JSON.stringify(myvar);
$.cookie('setting', serialized, { expires: 1, path: '/' });
To retrieve an object from a cookie :
JSON.parse($.cookie("setting"));
See this answer for examples of JSON.stringify and JSON.parse.