How to extract the message value from JSON in Node.js - node.js

My JSON is:
body =
{
"session_id":"45470003-6b84-4a2b-bf35-e850d1e2df8b",
"message":"Thanks for calling service desk, may I know the store number you are calling from?",
"callstatus":"InProgress",
"intent":"",
"responseStatusCode":null,
"responseStatusMsg":null,
"context":"getstorenumber"
}
How to get message value using Node js? Please let me know after testing.
i tried body.message and body['message'] and also body[0]['message']. I am always getting "undefined"

#Chris comment, since the problem is sorted out, Adding the answer to all members for future ref.
From node.js result, body is taken as JSON string, using JSON.parse.body converted to json object.
body =
{
"session_id":"45470003-6b84-4a2b-bf35-e850d1e2df8b",
"message":"Thanks for calling service desk, may I know the store number you are calling from?",
"callstatus":"InProgress",
"intent":"",
"responseStatusCode":null,
"responseStatusMsg":null,
"context":"getstorenumber"
}
JSON.parse.body
console.log(body.message);

Related

Mongoose model deleteOne() only works with hard coded string

I have a strange error with mongoose deleteOne() function. Today I wanted to work on my project and got an error while deleting an item from a collection. It simply doesn't delete the document until I use a hardcoded parameter for the options object like this:
const { deletedCount } = await Model.deleteOne({symbol: 'hardcoded'})
// results in deletedCount = 1
But if I try to use a dynamic string like:
const test = 'dynamic'
const { deletedCount } = await Model.deleteOne({symbol: test})
// results in deletedCount = 0
It does no longer delete the document from my collection. The strange thing is yesterday it worked fine and deleted the item.
I tried one other thing I read regarding errors with deleteOne():
const { deletedCount } = await Model.deleteOne({symbol: JSON.stringifiy(symbol)})
But this doesn't work, too.
Does anyone have an idea what's going wrong?
I always default to using ids whenever possible to make sure there's no mistake in the data I am targeting with a given operation.
So in this case that would mean using findByIdAndDelete() instead.
If I don't know the id of the document I'm trying to delete, then only I'd use findOneAndDelete() or deleteOne(), as you have, with something other than an id to identify the document I'm looking for.
Are you certain that the key-value pair you're passing to the function exists in your database?
Problem solved. I accidentally added an additional space character at the end of the string. This is very strange because the error was there since the beginning of my project and yesterday it worked.
So for everyone who might have a similar problem:
I have a ejs template file where I render a html element like this:
<div id="<%= symbol %> ">
Then in my event handler for requesting the server to deleting one item from my list I use the id attribute as a request parameter in the body. In the route handler this parameter is passed to mongoose:
const { symbol } = req.body
const { deletedCount } = await Model.deleteOne({ symbol })
As I mentioned. In the template file after the last ejs seperator there is an addional space character that caused the error. I spotted this issue by making a copy of the monoogse query and than logged it to the console. There I could see the wrong condition parameter.

How to get the id from the given lines of code?

{
acknowledged: true,
insertedId: new ObjectId("612d9d08db9c20f031033478")
}
This was the JSON format I got while I added a file and some other things to MongoDB and I want to get this id separately to save the file to another folder.
Can anyone please explain this?
I believe this question was answered by Vikas in this thread How to get value from specific key in NodeJS JSON [duplicate]
Edited The Answer. Now Its working for above object in question
You can use following function to access the keys of JSON. I have
returned 'mm' key specifically.
function jsonParser(stringValue) {
var string = JSON.stringify(stringValue);
var objectValue = JSON.parse(string);
return objectValue['mm'];
}
if this is a JSON String, at first of all you have to parse it to object liertal, then you can access the specified property you mentioned, so you can do like the following:
function parseJsonString(jsonString) {
// first parse it to object
var obj = JSON.parse(jsonString);
// now access your object property/key
var id = obj.insertedId;
}
If your doing it on mongodb shell or Robo3T then, the line of code would be:
db.collection_name.find({},{insertedId:1})
This is related to projection. 1 represents you want to display it as your output.
In your case as you want only the value of your object id to get displayed, you have to use .valueOf() ; that is ObjectId().valueOf().
-> insertedId: new ObjectId("612d9d08db9c20f031033478")
-> ObjectId("612d9d08db9c20f031033478").valueOf()
->
-> 612d9d08db9c20f031033478
Your can refer this : https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/ site for your reference.
So you can use this .valueOf() in your code and get the id saved in the document

Can Cloudant list/show functions return objects and arrays(any JSON)?

As per the API documentation for Cloudant: Show function can be used to render a document in a different format or extract only some information from a larger document. Same is the case for a list function, the only difference is that it applies on a set of documents. I created a design document with a show function as follows:
{ "shows": { "showDemo":"function(doc,req){return {'body': doc, 'headers':{'Content-Type':'application/json'}}}" } }
When I use this function, _design/showFunc/_show/showDemo/doc1, I get the following error:
{ "error": "unknown_error", "reason": "badarg", "ref": 1793182837 }
I have observed the same error when the show function returns an array. However, no error is given when HTML,Text, XML is returned. Can we say that list/show functions can only return data in a format other than JSON? This example shows the "Accept" header for req object request Object.
What's happening here is that the show function needs to return a response object. From the docs (see http://docs.couchdb.org/en/2.1.0/json-structure.html#response-object) the body field needs to be a string, so you can return whatever you like but it needs to be stringified or otherwise turned into a format that can be sent as HTTP.
If you want to send JSON then doing JSON.Stringify(doc) as the value for body should do what you expect.

Inserting a variable as a key in MongoDB

I am retrieving JSON data from an API and this is a short example of it:
{"hatenames":
{"id":6239,
"name":"hatenames",
"stat1":659,
"stat2":30,
"stat3":1414693
}
}
I am trying to insert it in the MongoDB (using MongoClient) but it won't let me put just the object directly or use a variable as a field name. If I put the var username it will just output it as username in the database field. This is what I would like to work:
collection.insert({object}
collection.insert({username:object[username]}
but it doesn't and I've been stuck on this for the past few hours. The only resolution I found was to set it and then update the field name afterwards, but that just seems lame to have to do every single time, is there no elegant or easy option that I am somehow missing?
First of all, being a programmer, you should forget about "it does not work" phrase. You should describe how it does not work with exact error messages you encounter. Not to your problem.
Just because I can easily do
db.coll.insert({"hatenames":
{"id":6239,
"name":"hatenames",
"stat1":659,
"stat2":30,
"stat3":1414693
}
})
or var a = {"hatenames":{"id":6239, "name":"hatenames", "stat1":659, "stat2":30, "stat3":1414693}}; and db.coll.insert(a),
I think that the problem is that your object is not really an object, but a string. So I suspect that you have a string returned to you back from that API. Something like '{"hatenames":{...}' and this caused a problem when you try to save it or access the properties. So try to convert it to JSON.
Try doing this:
MongoClient.connect('mongodb://127.0.0.1:27017/db_name', function(err, db) {
if(err) throw err;
someCollection = db.collection('some_collection');
});
someCollection.insert({
name: hatenames['name']
});
EDIT
For Dynamic approach, I would suggest you to play aroung this function:
Object.keys(hatenames)
this function will return keys in array.
EDIT 2
I have founded a link: Insert json file into mongodb using a variable
See, if that helps.

How to display arbitrary, schemaless data in HTML with node.js / mongodb

I'm using mongodb to store application error logs as json documents. I want to be able to format the error logs as HTML rather than returning the plain json to the browser. The logs are properly schemaless - they could change at any time, so it's no use trying to do this (in Jade):
- var items = jsonResults
- each item in items
h3 Server alias: #{item.ServerAlias}
p UUID: #{item.UUID}
p Stack trace: #{item.StackTrace}
h3 Session: #{item.Session}
p URL token: #{item.Session.UrlToken}
p Session messages: #{item.Session.SessionMessages}
as I don't know what's actually going to be in the JSON structure ahead of time. What I want is surely possible, though? Everything I'm reading says that the schema isn't enforced by the database but that your view code will outline your schema anyway - but we've got hundreds of possible fields that could be removed or added at any time so managing the views in this way is fairly unmanageable.
What am I missing? Am I making the wrong assumptions about the technology? Going at this the wrong way?
Edited with extra info following comments:
The json docs look something like this
{
"ServerAlias":"GBIZ-WEB",
"Session":{
"urltoken":"CFID=10989&CFTOKEN=f07fe950-53926E3B-F33A-093D-3FCEFB&jsessionid=84303d29a229d1",
"captcha":{
},
"sessionmessages":{
},
"sessionid":"84197a667053f63433672873j377e7d379101"
},
"UUID":"53934LBB-DB8F-79T6-C03937JD84HB864A338",
"Template":"\/home\/vagrant\/dev\/websites\/g-bis\/code\/webroot\/page\/home\/home.cfm, line 3",
"Error":{
"GeneratedContent":"",
"Mailto":"",
"RootCause":{
"Message":"Unknown tag: cfincflude.",
"tagName":"cfincflude",
"TagContext":[
{
"RAW_TRACE":"\tat cfhome2ecfm1296628853.runPage(\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/home\/home.cfm:3)",
"ID":"CFINCLUDE",
"TEMPLATE":"\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/home\/home.cfm",
"LINE":3,
"TYPE":"CFML",
"COLUMN":0
},
{
"RAW_TRACE":"\tat cfdisplay2ecfm1093821753.runPage(\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/display.cfm:6)",
"ID":"CFINCLUDE",
"TEMPLATE":"\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/display.cfm",
"LINE":6,
"TYPE":"CFML",
"COLUMN":0
}
]
}
}
... etc, but is likely to change depending on what the individual project that generates the log is configured to trigger.
What I want to end up with is a formatted HTML page with headers for each parent and the children listed below, iterating right through the data structure. The Jade sample above is effectively what we need to output, but without hard-coding that in the view.
Mike's analysis in the comments of the problem being that of creating a table-like structure from a bunch of collections that haven't really got a lot in common is bang-on. The data is relational, but only within individual documents - so hard-coding the schema into anything is virtually impossible as it requires you to know what the data structure looks like first.
The basic idea is what #Gates VP described. I use underscore.js to iterate through the arrays/objects.
function formatLog(obj){
var log = "";
_.each(obj, function(val, key){
if(typeof(val) === "object" || typeof(val) === "array"){
// if we have a new list
log += "<ul>";
log += formatLog(val);
log += "</ul>";
}
else{
// if we are at an endpoint
log += "<li>";
log += (key + ": " + val);
log += "</li>";
}
});
return log;
}
If you call formatLog()on the example data you gave it returns
ServerAlias: GBIZ-WEBurltoken: CFID=10989&CFTOKEN=f07fe950-53926E3B-F33A-093D-3FCEFB&jsessionid=84303d29a229d1sessionid: 84197a667053f63433672873j377e7d379101UUID: 53934LBB-DB8F-79T6-C03937JD84HB864A338Template: /home/vagrant/dev/websites/g-bis/code/webroot/page/home/home.cfm, line 3GeneratedContent: Mailto: Message: Unknown tag: cfincflude.tagName: cfincfludeRAW_TRACE: at cfhome2ecfm1296628853.runPage(/home/vagrant/dev/websites/nig-bis/code/webroot/page/home/home.cfm:3)ID: CFINCLUDETEMPLATE: /home/vagrant/dev/websites/nig-bis/code/webroot/page/home/home.cfmLINE: 3TYPE: CFMLCOLUMN: 0RAW_TRACE: at cfdisplay2ecfm1093821753.runPage(/home/vagrant/dev/websites/nig-bis/code/webroot/page/display.cfm:6)ID: CFINCLUDETEMPLATE: /home/vagrant/dev/websites/nig-bis/code/webroot/page/display.cfmLINE: 6TYPE: CFMLCOLUMN: 0
How to format it then is up to you.
This is basically a recursive for loop.
To do this with Jade you will need to use mixins so that you can print nested objects by calling the mixin with a deeper level of indentation.
Note that this whole thing is a little ugly as you won't get guaranteed ordering of fields and you may have to implement some logic to differentiate looping on arrays vs. looping on JSON objects.
You can try util.inspect. In your template:
pre
= util.inspect(jsonResults)

Resources