getting nested objects in mongoose - json

I'm trying to retrieve an array of objects in mongoose using code that looks like this.
mongoPlaces
.find({
'person.types': {$in: ["student"]}
})
.select('family')
.lean()
.limit(3)
.exec(function (err, families) {
console.log()
})
the results is something like this
[
0: family:{objects}
1: family:{objects}
2: family:{objects}
]
and I need something like this
[
0: {objects}
1: {objects}
2: {objects}
]
is there some way to retrieve the contents of an object instead of the object itself using mongoose without having to make a loop and correct the array or is there any other way to make this cleanly?

There's no way to do this with mongoose, but there are ways of making it cleanly:
mongoPlaces
.find({
'person.types': {$in: ["student"]}
})
.select('family')
.lean()
.limit(3)
.exec(function (err, docs) {
var families = docs.map(function pluckFamily(doc) {
return doc.family;
});
return families;
});
In this example, map feeds each retrieved document to the function pluckFamily, and forms another array with all the values that that function returned.
If you're going to do a lot of this, you may want to check out the underscore library. It includes a pluck function.

Related

Should I convert JSON to Array to be able to iterate it with v-for?

In the following code I am getting data from server and filling array with them:
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response); // putting JSON answer to Component data in userContent
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
Now I am filling. data is declared in var userContent = Vue.extend({. I am using App.$refs.userContent.rasters_previews_list to set it's value, because one man from SO said that there is no other way to get access to constructor. I tried to do output of rasters_previews_list after changing with watch, but here is what I am see. http://img.ctrlv.in/img/16/08/04/57a326e39c1a4.png I really do not understand am I setting it's right way or no. If yes, why I do not see data and see only this crap?
data: function () {
return {
rasters_previews_list: []
}
}
But How I can iterate it with v-for?
<ul v-for="img in rasters_previews_list">
<li>{{img}}</li>
<ul>
This code is display one bullet. So it's look like it's assume that there is one object.
My object in browser console look like:
Object {request: Object, data: Array[10], status: 200, statusText: "OK", ok: true}
Your setting the full response instead of just the data you actually need.
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response.data);
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
If this isn't what you are looking for please post a full example.

calling a dojo JsonRest with parameters

When calling JsonRest using dojo, how can I pass parameters with it.
var rest = new JsonRest({
target: "/path/to/service"
});
JsonRest example:
require(["dojo/store/JsonRest"], function(JsonRest){
// create a store with target your service
var store = new JsonRest({
target: "/path/to/service"
});
// make a get request passing some options
store.query("foo=bar", {
start: 5,
count: 5,
sort: [
{ attribute: "color", descending: true }
]
}).then(function(results){
// result here
});
});
The function to use in your case is query with signature query(query, options)
When called, query will trigger a GET request to {target}?{query}, as described in dojo docs.
Please keep in mind that:
If query is an object, it will be serialized.
If query is a string, it is appended to the URL as-is.
If options includes a sort property, it will be serialized as a query parameter as well;
Your service/API should:
Return a array of objects in JSON format.
Return an empty array if no match is found.

Reaching a specific property of the data json object

I would like to reach a specific property of the data that I have returned from my service.
So basically I want to be able to somehow reach $scope.users.name, I know that the users are the objects in the array, but could I reach that specific property in any way? Hopefully the question is clear enough?
$scope.users = [];
UserService.getAll().then(
function (data) {
$scope.users = data;
}, function (err) {
console.log(err);
}
);
I am assuming the data you receive is in the form of an array. If you know the index then you can do
$scope.users[2].name
Where 2 is the index of the object you want to know the name property of.
Or you can try a js function forEach
$scope.users.forEach(function (user) {
console.log(user.name);
});
The function will iterate over all the objects and you can access their properties inside the callback which is passed in.
Hope that is what you're looking for.

Filter JSON data based on current URL route

The problem
I'm trying to filter json data and display only a portion of it on an Angular page, based on the page's current URL.
In detail
I have a list of 100 JSON objects, and each one looks like this:
{
"name": "Evangeline Perreault",
"age_1": 1,
"total_age": 1,
"photo_small": "img/400/001_400.jpg",
"photo_medium": "img/800/001_800.jpg",
"photo_large": "img/1200/001_1200.jpg",
"photo_extralarge": "img/1600/001_1600.jpg",
"video": 67443664,
"id": 1,
"quote": "test quote here and here",
"type": 1
},
The 'type' attribute is what I want to use to filter out the subsets of my data. With that in mind, I tried to setup my URL structure to tie the type attribute here to my url. Here is my route:
angular.module('100_Ages', ['mydirectives', 'ngResponsiveImages']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/100_Ages/nav/:personType', {templateUrl: 'partials/person-list.html', controller: NavListCtrl}).
otherwise({redirectTo: '/100_Ages'});
}]);
So, I have pointed the route to the 'type' field in my JSON and I tried writing a controller to tie the two together.
function NavListCtrl($scope, $routeParams, $http) {
$http.get('person.json').success(function(data) {
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.person = person;
});
});
}
And here is my partial template:
<div class="nav_outer"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected this to display all the matching images for the URL type I'm on. So, if I'm on "/100_Ages/nav/3", I expected all the images (roughly 10 pictures) from the objects with a type of "3" to display. However, it only displayed the last object with a type of "3".
So, I tried an ng-repeat like so:
<div class="nav_outer" ng-repeat="person in persons"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected that to loop through and show all the matching images, but that made nothing at all show up.
I think my problem has to do with the angular.forEach, but I'm not sure how else to tie my JSON type to the page's typeid.
Thanks for any suggestions.
The ng-repeat should work if you push each item into an array. (Also, you are referring to a 'persons' object in the ng-repeat, which doesn't exist according to code provided). So, try this:
$http.get('person.json').success(function(data) {
$scope.persons = [];
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.persons.push(person);
// or alternatively - this.push(person), with the optional 3rd param of $scope.persons (I don't really understand that, but whatever...)
});
});
Now with the array populated, your ng-repeat="person in persons" should work.
UPDATE:
If the success object was already an array of objects, then just set the scope object to the array - no need to iterate through them:
$http.get('person.json').success(function(data) {
$scope.persons = data;
})

parse urls in Backbone.js

I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.