Access nested objects in API using vue resource - json

I'm just starting out with vue resource (and ajax in general) and I'm having trouble listing an array that's nested in my API.
If this is my sample JSON:
{
"item1" : "data",
"item2" : 1234,
"item3" : 5678,
"item6" : "data",
"item7" : [ {
"id" : 0,
"data2" : "testdata",
"data3" : "testdata",
},{
"id" : 2,
"data2" : "testdata",
"data3" : "testdata",
},{
"id" : 3,
"data2" : "testdata",
"data3" : "testdata",
} ]
}
I want to pass the item7 array through a list in my html like this:
<div id="app">
<ul v-for="item in items">
<li>{{ item.data2 }} {{ item.data3 }}</li>
</ul>
</div>
Here's my js:
window.onload = function() {
new Vue({
el: '#app',
data: {
items: {}
},
ready: function () {
this.$http.get('/api/items', function(data) {
console.log(data);
this.items = data.item7[];
});
},
});
};
Naturally this returns nothing, I'm not sure how to loop the array through this.items = data.item7[]; with vue resource.

You just need to write this.items = data.item7, no need for [].
You also need to bind this to the function. When you're in the callback from the HTTP request, this refers to something else. So you can use .bind(this) like so:
this.$http.get('/api/items', function(data) {
this.items = data.item7;
}.bind(this));
Lastly, you should instantiate items as an array if it is going to be an array:
data: {
items: []
},

Related

saving in the database variable as ObjectID() MongoDB, NodeJS

I created function which is adding people_id inside array of given card. But there is problem that inserted id is always not as an objectId() where I just need it to be saved as objectId.
When id is added to array i I'm sending whole variable board JSON to nodejs API where is executed function findOneAndUpdate. And here is problem because after saved this arrays is not objectID in Author. Can someone tell me how to make it?
JSON board
{
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [
ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [
{
"list" : "1",
"cards" : [
{
"name" : "2",
"Author" : [
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22e"
]
},
{
"name" : "3",
"Author" : []
}
]
},
{
"list" : "fea",
"cards" : [
{
"name" : "card",
"Author" : []
}
]
}
],
"__v" : 0 }
Router:
router.post('/add/member', function (req, res, next) {
console.log(req.body)
Board.findOneAndUpdate({ _id: req.body._id },
{
$set: {
lists : req.body.lists
}
},
{
upsert: true
},
((cards) => {
res.send(cards)
})
)
});
model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
name: { type: String, maxlength: 20 },
lists : { type: Array },
users : [{ type : Schema.Types.ObjectId, ref: 'User' }],
});
module.exports = mongoose.model('Board', BoardSchema);
And here is function with adding poeple
$scope.addMemberToCard = (indexList, indexCard, member) => {
$scope.board.lists[indexList].cards[indexCard].Author.push(member);
console.log( $scope.board.lists[indexList].cards[indexCard].Author)
return ApiService.staff.addMemberToCard($scope.board).then(function () {
})
}
You could use the mongoose Types ObjectID method and then transform the string sent into an ObjectID.
const id = new new mongoose.Types.ObjectId(Author);

How to get sub document only in mongoose?

I'm trying to extract only sub document from an array has the following schema :
const UserSchema = Schema({
name: {
type: String
},library:[{
story:{type: Schema.Types.ObjectId,ref: 'Story'}
}],
});
i tried to use :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
};
and it gives this result :
{
"_id": "5949615072e15d2b34fa8f9d",
"library": [
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
}
but what i'm expecting to get is only this :
[
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
I already tried to use double selection like :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
.select('story')
};
But is gives the same result
Try this one :
module.exports.getUserStories = function(userId, callback){
User.find({_id: userId },{'library.story'}).then(function(user){
if(user){
callback(user.library);
}});
};
Docs here
This output is expected to return by "select" but simply you can prepare the returned data to be as you need as following:
User.findOne({_id: userId }).select('library').then(function(result){
if(result){
//If there is returned item
var stories = result.library;
//Continue ...
}
},function(error){
//Error handling
})

Angular.js table mapping brain fahrt

I'm new to front end development and am playing with angular.js (1.4.8). In the code below, I do an http get. I then
map the json data into a table. I think I have a mapping problem, ie, the ng-repeat isn't pulling stuff out of the
json correctly. Or perhaps it's something else and I'm unintentionally misleading you. Do you see a programming
error here?
Here is the relevant html:
<div class="table-responsive" data-ng-app="myApp" data-ng-controller="customersCtrl">
<table class="table table-striped">
<thead>
<tr>
<th data-ng-repeat="header in headers">{{header}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="record in records track by $index">
<td>{{ record.data.day }}</td>
<td>{{ record.data.date }}</td>
<td>{{ record.data.value }}</td>
</tr>
</tbody>
</table>
</div>
Here is my angular file:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$scope.init = function () {
$http.get("https://localhost:4567/1")
.then(function (response) {
var json = angular.toJson(response.data.records);
$scope.records = json;
$scope.headers = response.data.headers;
});
};
$scope.httpPost = function (journal) {
var theJson = angular.toJson(journal);
var successCallback = function (data, status, headers, config) {
$scope.postResponse = data;
};
var errorCallback = function (data, status, headers, config) {
console.log();
};
$http.post('https://localhost:4567/journal', {"foo": "bar"}).then(successCallback, errorCallback);
};
$scope.master = {};
$scope.update = function (journal) {
$scope.master = angular.copy(journal);
};
$scope.reset = function () {
$scope.journal = angular.copy($scope.master);
};
$scope.init();
$scope.reset();
});
Here is the response body (json):
{
"headers" : [ "day", "date", "value" ],
"records" : [ {
"data" : {
"day" : "Tuesday",
"date" : "5/3/2011",
"value" : "2.6"
},
"id" : "646312cc-1931-4137-af2a-e712300b489b",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "3bee5500-fd03-4d69-84af-8b8dc85292b0"
}, {
"data" : {
"day" : "Wednesday",
"date" : "5/4/2011",
"value" : "2.6"
},
"id" : "f58eae54-6b30-4f61-b8cc-b04984a8436a",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "29e4dc69-c118-4fad-91ae-8a1efaf9b984"
}, {
"data" : {
"day" : "Thursday",
"date" : "5/5/2011",
"value" : "2.6"
},
"id" : "ebf8dba4-52a9-4e0b-a575-cda2ea29a2ea",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "986961bb-84ff-4ac6-9f70-96827006ed87"
} ],
"id" : null,
"dateCreated" : null,
"dateUpdated" : null,
"etag" : null
}
=====
As pointed out by two people, the problem was this line (I had turned json object to debug something and forgot to revert ;(
var json = angular.toJson(response.data.records);
Angular's $httpProvider automatically adds the Content-Type: application/json header to all outgoing service requests made by your application.
In addition, it will also automatically deserialise responses using a JSON parser if a JSON-like response is detected.
As such, there is no need to use functions like angular.toJson() to do the JSON conversion yourself unless you have overridden the default provider behaviour somewhere.
Glad that helped. :-)

Sencha touch2: How can i parse my nested json data?

i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'

jsTree with Json-Data, don't get metadata

i read many suggestions concerning jsTree/Json/metadat, but I don't found a working solution. I want to get the metadata (e.g. id) if a node is clicked.
1st my Json Data:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
},
"metadata":{
"id":"1000000000000000021"
}
}
}
]
2nd JS function which create the tree and should get the clicked id(ajax call and some oracle apex stuff)
function populateTree(pRegionId) {
console.log('---Js Tree---');
$.ajax({
type : 'POST',
async : true,
url : 'wwv_flow.show',
data : {
"p_request" : 'APPLICATION_PROCESS=GET_TREE',
"p_flow_id" : $v('pFlowId'), // app id
"p_flow_step_id" : $v('pFlowStepId'), // page id
"p_instance" : $v('pInstance'), // session id
},
ggg : pRegionId,
success : function (data) {
console.log(data);
var jsonobj = JSON.parse(data);
apex.jQuery("#" + this.ggg).jstree({
"themes" : {
"theme" : "default",
"dots" : false,
"icons" : true
},
"json_data" : {
"data" : [jsonobj]
},
"plugins" : ["themes","json_data", "ui"]
//}).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("jstree").id); });
}).bind("select_node.jstree", function (e, data) {
console.log(data);
});
}
});
}
3rd the object where the id should be (firebug domview):
args [a#1000000000000000301.jstree-clicked #, true, Object { originalEvent=Event click, type= "click", timeStamp=30977664, mehr...}]
inst Object { data={...}, get_settings=function(), _get_settings=function(), mehr...}
rlbk false
rslt Object { obj={...}, e={...}}
e Object { originalEvent=Event click, type="click", timeStamp=30977664, mehr...}
obj jQuery(li.jstree-closed)
as you can see there is no id. So I guess something with the metadata part is messy but i cannt figure out where the mistake is.
Thanks in advance
Mario
Finally I tracked my mistake down. If you can see in the json code from above:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
},
"metadata":{
"id":"1000000000000000021"
}
}
}
]
The metadataobject(?) is within the dataobject like the attr, all online validations show me that my jason code is valid. But the metadatas right place is after the data:
[
{
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
}
},
"metadata":{
"id":"1000000000000000021"
}
}
]
And now I get the id with the following js
.bind("select_node.jstree", function (e, data) {
console.log(data.rslt.obj.data("id"));
});
And if you want an id within the li tag put an attr-object bevor the data-object like:
[
{
"attr":{
"id":"1000000000000000021"
},
"data":{
"title":"TEST",
"icon":"/i/small_folder.gif",
"attr":{
"id":"1000000000000000021"
}
},
"metadata":{
"id":"1000000000000000021"
}
}
]
cu soon
mario