Question is simple, but not answered perfectly yet for me (perhaps only for me but is not totaly clear..)
Question : I want to return MongoDB from "collection.findOne" with mongo.. is ok AND JSON.stringify() this informations for send to another service...
// i past a pseudo code for response :-)
collection.find({id_to_find: id_to_find}, function(err, results) {
if (err){
console.log ("error find");
}if (results) { // update for good syntax !
var results = JSON.stringify(results); // error, why ??? <if not this line, is ok, but i want stringify !>
res.json({
returnJSON: results
});
}
}
////////////////////////////////////
// example of a mongo object return :
[ { _id: 1,
property: 'xxxx',
etc: 'xx'
},
{ _id: 2
property: 'xxxx',
etc: 'xxxx'
}
]
Next time, i have severals records like
results_mongo = [{mongo object datas},{ etc.. }] // like an array
i want with my server node.js to JSON.stringify my collection && return theses results..
The error is :::::
TypeError: Converting circular structure to JSON
at Object.stringify (native)
Response ?
(thank to correct object to result, my question is how to exept the stringify deep object.. :)
for searchs, a goods posts on stack :
Convert Mongoose docs to json
How do you turn a Mongoose document into a plain object?
// you are passing object to your stringify method.
var object = JSON.stringify(object);
// you need to pass results as your callack method returns results
var object = JSON.stringify(results);
Related
I've been trying retrieve values from JSON and so far, been unsuccessful. It does get called on the front-end when I refresh the page, but the information is not passing to the next method. I think the issue might be down to the promises.push... line, as I've tried to debug the method underneath and the information is not being passed on at all.
AngularJS:
var promises = [];
promises.push(SpringDataRestService.get({"collection": "subjects"}).$promise);
// Require each of these queries to complete before continuing
$q.all(promises).then(function (data) {
// Grab the first result
$scope.available = data[0].subjects;
$scope.selected = [];
// If this is an update, get the second result in set
if (data.length > 1) {
// For each permission that is assigned to this role, add ID (name) to selected
for (var i = 0; i < data[1].data.subjects.length; i++) {
var perm = data[1].data.subjects[i];
$scope.selected.push(perm.name);
}
}
$scope.tableEditOptions = new NgTableParams({}, {
dataset: $scope.available
});
$scope.available, 'name');
}).catch(function (data) {
// ERROR
});
JSON:
[
{
"name": "FWGWG",
"description": "WGWGWG",
"lockId": 0
},
{
"name": "QFQFQF",
"description": "QFQFQFQ",
"lockId": 0
}
]
I'm confident as well my for loop is wrong due to assigning the values as well, since I don't think it should be data.subjects, but I understand these threads are only 1 issue per question. Any help would be greatly appreicated.
Use the query method for arrays:
var promise = SpringDataRestService.query({"collection": "subjects"}).$promise;
promise.then(function (dataArr) {
console.log(dataArr);
//...
}).catch(function (errorResponse) {
console.log(errorResponse);
});
With the REST services, the get method returns a JavaScript object and the query method returns a JavaScript array.
From the Docs:
$resource Returns
A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:
{
'get': {method: 'GET'},
'save': {method: 'POST'},
'query': {method: 'GET', isArray: true},
'remove': {method: 'DELETE'},
'delete': {method: 'DELETE'}
}
...
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
For more information, see
AngularJS $resource Service API Reference
I am pretty new to JSON / Jquery world so please bear with my ignorance.
I am trying to read an output from a Json data returned by webservice call like below :
My webservice call is here:
http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297
This return the data as :
{
"data": [
{
"PORTFOLIO_ID": 13495,
"SUBSCRIPTION_ID": 1653,
"STATUS": "ACTIVE",
}
],
"success": true
}
Now I am trying to get alert onthe Json Data returned as string and also want to get this as Parsed /
<script>
var parsed ;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(data);
alert(parsed) ;
</script>
I am getting the response in Alert as "Undefined" . I may not be doing right handling the success handler . I want to get each value and specific value of the json data returned.
Please help.
Thanks
I am getting the response in Alert as "Undefined".
Reason : You are trying to parse the API response out of the scope. As data object is only accessible in the promise returned by the API call.
Try this hope it will work as per your expectation :
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(res) {
var data = res.data;
alert(JSON.stringify(data));
});
You are calling data out side the scope.
<script>
var parsed ;
var myData;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
myData = data;
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(myData);
alert(parsed) ;
</script>
I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.
Im using express, body-parser and moongose to build a RESTful web service with Node.js. Im getting json data in the body of a POST request, that function looks like this:
router.route('/match')
// create a match (accessed at POST http://localhost:3000/api/match)
.post(function(req, res) {
if (req._body == true && req.is('application/json') == 'application/json' ) {
var match = new Match(); // create a new instance of the match model
match.name = req.body.name; // set the match name and so on...
match.host = req.body.host;
match.clients = req.body.clients;
match.status = req.body.status;
// save the match and check for errors
match.save(function(err) {
if (err) {
//res.send(err);
res.json({ status: 'ERROR' });
} else {
res.json({ status: 'OK', Match_ID: match._id });
}
});
} else {
res.json({ status: 'ERROR', msg: 'not application/json type'});
}
});
The model Im using for storing a match in the database looks like this:
// app/models/match.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MatchSchema = new Schema({
name: String,
host: String,
clients: { type: [String]},
date: { type: Date, default: Date.now },
status: { type: String, default: 'started' }
});
module.exports = mongoose.model('Match', MatchSchema);
But how do I validate that the json data in the body of the POST request has the key/value fields I want? For clarification, I dont want to insert data in the database that is incomplete. If I test to skip a key/value pair in the json data I get a missing field in the database and when I tries to read req.body.MISSING_FIELD parameter in my code I get undefined. All fields except date in the model is required.
Im using json strings like this to add matches in the database
{"name": "SOCCER", "host": "HOST_ID1", "clients": ["CLIENT_ID1", "CLIENT_ID2"], "status": "started"}
I use a very simple function that takes an array of keys, then loops through it and ensures that req.body[key] is not a falsy value. It is trivial to modify it to accommodate only undefined values however.
In app.js
app.use( (req, res, next ) => {
req.require = ( keys = [] ) => {
keys.forEach( key => {
// NOTE: This will throw an error for ALL falsy values.
// if this is not the desired outcome, use
// if( typeof req.body[key] === "undefined" )
if( !req.body[key] )
throw new Error( "Missing required fields" );
})
}
})
in your route handler
try{
// Immediately throws an error if the provided keys are not in req.body
req.require( [ "requiredKey1", "requiredKey2" ] );
// Other code, typically async/await for simplicity
} catch( e ){
//Handle errors, or
next( e ); // Use the error-handling middleware defined in app.js
}
This only checks to ensure that the body contains the specified keys. IT won't validate the data sent in any meaningful way. This is fine for my use case because if the data is totally borked then I'll just handle the error in the catch block and throw an HTTP error code back at the client. (consider sending a meaningful payload as well)
If you want to validate the data in a more sophisticated way, (like, say, ensuring that an email is the correct format, etc) you might want to look into a validation middle-ware, like https://express-validator.github.io/docs/
I am trying to send a JSON object back to my client using a websites API and am getting the following error.
var body = JSON.stringify(obj, replacer, spaces);
TypeError: Converting circular structure to JSON
at Object,stringify (native)
Here is my code
app.get('/api/test', function(req, res){
http.get('http://api.biblia.com/v1/bible/content/LEB.txt.json?passage=John3.16&key=fd37d8f28e95d3be8cb4fbc37e15e18e', function(data) {
res.json(data);
});
});
If I replace data with a simple JSON object {"test":"test"}. Everything works fine. Any help with understanding what is even occuring would be helpful. I am using an Express.js Node.js Angular.js stack. Thank you!
The data variable in your callback is actually an instance of http.IncomingMessage, which is much more complex than just data. The error you're getting is because it has circular references, so you need to filter it out. There is an answer here that outlines this process using the code below:
var cache = [];
JSON.stringify(o, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection