Im trying to remove a nested object from an array by the _id property, however I wasnt able to make it work and other posts here were of no help either, my db look something like this:
storage:Array
0:Object
folders:Array
0:Object
stored:Array
0:Object
files:Object
name:"1"
snippet:"snippet 1"
_id:60bcafda1e2b8b4a288cd822
1:Object
files:Object
name:"2"
snippet:"snippet 2"
_id:60bcafda1e2b8b4a288cd823
2:Object
files:Object
name:"3"
snippet:"snippet 3"
_id:60bcafda1e2b8b4a288cd824
3:Object
files:Object
name:"4"
snippet:"snippet 4"
_id:60bcafda1e2b8b4a288cd825
4:Object
files:Object
name:"5"
snippet:"snippet 5"
_id:60bcafda1e2b8b4a288cd826
5:Object
files:Object
name:"6"
snippet:"snippet 6"
_id:60bcafda1e2b8b4a288cd827
6:Object
folders:Object
name:"indented folder"
_id:60bcafda1e2b8b4a288cd828
stored:Array
0:Object
files:Object
name:"indented file 1"
snippet:"At vero eos et accusamus et iusto odio dignissimos ducimus qui blandit..."
_id:60bcafda1e2b8b4a288cd829
_id:60bcafda1e2b8b4a288cd82a
name:"test"
_id:60bcafda1e2b8b4a288cd821
files:Array
0:Object
name:"message"
snippet:"Hello World!"
_id:60bcafda1e2b8b4a288cd82b
Any help would be greatly appreciated!
You can use $pull, something like :-
Model.findByIdAndUpdate(_id,{
$pull: {
arrayKeyName: {_id: _idOfObjectInArray}
}
}, {new: true});
Related
I am trying to build a filter for JSON object at the moment, the json object looks like this,
created_at: null
deleted_at: null
id: 3
listings: Array(3)
0: {id: 3, name: "Learn the basics of the guitar from the anatomy of the guitar to scales, chords", slug: "learn-the-basics-of-the-guitar-from-the-anatomy-of-the-guitar-to-scales-chords", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "undefined", …}
1: {id: 8, name: "Advanced guitar skills with William Topa", slug: "advanced-guitar-skills-with-william-topa", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
2: {id: 9, name: "Music production simplified", slug: "music-production-simplified", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
length: 3
__proto__: Array(0)
tag: "Music"
updated_at: null
weight: null
This is part of a bigger object, the hierarchy looks like
[{ data, listings }, {data, listings}]
What I am wanting to do, is filter through the listings array and hide any listings that don't have a cost of "0.00"
Here is what i am trying,
<input type="checkbox" v-model="priceFilter" value="0.00" />
data() {
return {
this.priceFilter: []
}
},
computed: {
filteredTags() {
return this.tags.filter(tag => {
tag.listings.filter(listing => "0.00" === listing.cost);
//console.log(this.checkedPrice, listing.cost);
});
},
},
In the above I just trying to return the listings where the cost matches 0.00 with trigger it via the checkbox being checked but even that does not filter as I wish I still see all listings.
Anyone care to offer any advice?
I create an Meteor application where have two collections, ActivityCards and Users. I have a reference to the User inside my ActivityCard collections like this:
{
"_id" : "T9QwsHep3dMSRWNTK",
"cardName" : "Guntnauna",
"activitycardType" : 10,
"startDate" : "1952-08-09",
"remainingHours" : 0,
"activities" : [
{
"activityName" : "Cfuw",
"activityTotal" : "5",
"activityEmployee" : "Smamnktl",
"activityDate" : "1960-07-16"
},
...
],
"customerID" : "z9hXczmWaf7wgdAtj",
"isArchived" : 0
}
customerID contains an id to the following user collection:
{
"_id" : "9mXAZkmfpKMPvQY8Y",
"createdAt" : ISODate(),
"services" : {
"password" : {
"bcrypt" : ""
}
},
"emails" : [
{
"address" : "topony#mailinator.com",
"verified" : false
}
],
"profile" : {
"relationNumber" : "962",
"companyName" : "Snider Kinney Co",
"locationStreet" : "Ullamco eaque consequatur aspernatur consectetur eiusmod eligendi enim rerum consectetur asperiores officia eius itaque expedita dolorum",
"locationPostal" : "Sit inventore asperiores est anim commodo non fugiat consequat Voluptatem tempore sunt culpa magni",
"locationCity" : "Ipsum et fugit pariatur Nobis eveniet neque veniam perferendis eius ut quo excepteur consequatur voluptatem architecto",
"contactName" : "Julian Moran",
"contactPhone" : "+388-14-8339022",
"isArchived" : 0
},
"roles" : {
"customers" : [
"customer"
]
}
}
I am new to MongoDB and don't know if this is a properly configured relation In the documentation I mostly find relations from parent to child and not the other way around.
I am wondering what would you guys suggest for this type of relation.
How to save them, get the data from both collections, etc.
If my code can be used I would like to know how to get the relations from child to parent and display them. currently I only used the find() method from MongoDB and mapped the data into separate values.
You can have such a relation in your mongodb collection. If you are using mongoose you can define them in your schema like this:
customerId:{{ type: mongoose.Schema.ObjectId, ref: 'user' }}
and you can reach the parent from child with mongoose populate.
for more information see
https://mongoosejs.com/docs/populate.html
I have tried the filter logic from angular to one of the unordered list.
But, the search filter is working after typed 3 characters of the name, sometimes giving wrong search results.
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter :searchString">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
JSON:
{
"People":[
{
"name":"Andrew Amernante",
"rating":3,
"img":"http://www.fillmurray.com/200/200",
"Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
},
{
"name":"Frank Wang",
"rating":5,
"img":"http://www.fillmurray.com/200/201",
"Description":"Before errors, mails were only pressures. This is not to discredit the idea that a magic is the prose of anelizabeth. This could be, or perhaps some posit the outmost coil to be less than dedal. Some assert that those treatments are nothing more than carp.",
"Likes":[
"Frank",
"Manchester United",
"Football",
"Programming"
],
"Dislikes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
]
},
{
"name":"Sissi Chen",
"rating":5,
"img":"http://www.fillmurray.com/200/202",
"Description":"Aaah! Natural light! Get it off me! Get it off me! Oh, loneliness and cheeseburgers are a dangerous mix. D'oh. Here's to alcohol, the cause of all life's problems.",
"Likes":[
"Cats",
"the beach",
"Chopin",
"Blue things"
],
"Dislikes":[
"Birds"
]
},
{
"name":"Diego Garcia",
"rating":2,
"img":"http://www.fillmurray.com/200/204",
"Description":"Facts are meaningless. You could use facts to prove anything that's even remotely true! I prefer a vehicle that doesn't hurt Mother Earth. It's a gocart, powered by my ownsense of selfsatisfaction. You don't win friends with salad.",
"Likes":[
"Talking Spanish",
"Spanish food",
"Spanish things",
"Football"
],
"Dislikes":[
"Not talking spanish",
"Chopin"
]
},
{
"name":"Fuad Rashid",
"rating":4,
"img":"http://www.fillmurray.com/200/206",
"Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
Here is the plnkr code.
Ex: Start typing 'si', you will end up with two results where first one(frank wang) is not correct.
And, this is the reference plnkr where I'm referring for.
You would need to specify which object property, in this case name for the filter to filter against:
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter: { name: searchString }">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
You would need to set the initial value of searchString to an empty string as well to match against all people when no text has been entered.
$scope.searchString = '';
Here is a Plunker demonstrating the functionality.
Hopefully that helps!
You can create your own customized filter to specify on which property you need to search:
$scope.searchTextByName = function(artist){
if($scope.searchText !== undefined){
if(artist.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) > -1 ){
return artist;
}
}
}
Otherwise, it will match on all JSON value of single people object with your searchText key.
I have this JSON object being retreived from the server
{
"Totals": {
"TotalNotifications": 10,
"TotalUnreadNotifications": 5
},
"NotificationData": [{
"NotificationId": 1,
"NotificationType": "Alert",
"NotificationName": "Low Battery",
"NotificationDate": "2014-09-08T19:38:57.659",
"NotificationRead": false,
"NotificationActive": true,
"AlertData": {
"AlertType": "Battery",
"AlertSeverity": "Critical"
}
}, {
"NotificationId": 2,
"NotificationType": "Dtcprimary",
"NotificationName": "Mass or Volume Air Flow",
"NotificationDate": "2014-09-01T12:00:00.000",
"NotificationRead": false,
"NotificationActive": true,
"DtcData": {
"DtcCode": "P0101",
"Vehicle": "2000 Cadillac Deville 4.6L",
"DtcDescription": "Mass or Volume Air Flow A Circuit Range Performance",
"ShortDescription": "Ceat ame aut placcat doluptus, quo berum quiandae quid quissim agnimus danimol uptae. Neque si omnis sequo torabori tem nobitatet arcit aut incimaxim fugia sitatium",
"IdentifixId": "Click <a target=\"_blank\" href=\"https://www.google.com\">here</a> to request a list of top fixes."
}
}, {
"NotificationId": 3,
"NotificationType": "Dtcsecondary",
"NotificationName": "Mass or Volume Air Flow",
"NotificationDate": "2014-08-01T12:00:00.000",
"NotificationRead": true,
"NotificationActive": false,
"DtcData": {
"DtcCode": "P0101",
"Vehicle": "2000 Cadillac Deville 4.6L",
"DtcDescription": "Mass or Volume Air Flow A Circuit Range Performance",
"ShortDescription": "Ceat ame aut placcat doluptus, quo berum quiandae quid quissim agnimus danimol uptae. Neque si omnis sequo torabori tem nobitatet arcit aut incimaxim fugia sitatium",
"TopReportedFix": "Replace Air Intake Boot",
"FrequentlyReportedFixes": "<ul><li>Cleaned Mass Air Flow (MAF) Sensor</li><li>Programmed Powertrain Control Module (PCM)</li></ul>",
"AlsoReportedFixes": "<ul><li>Cleaned Mass Air Flow (MAF) Sensor</li><li>Cleaned throttle body</li><li>Flushed fuel tank w/P0171, P0174</li></ul>"
}
}, {
"NotificationId": 4,
"NotificationType": "Recall",
"NotificationName": "Mass or Volume Air Flow A Circuit Range Performance",
"NotificationDate": "2014-09-01T12:00:00.000",
"NotificationRead": false,
"NotificationActive": true,
"RecallId": 31234
}]
}
When I loop over the Notification object nothing happens. When I try regular handlebars it works just fine, http://jsbin.com/lemafe/1/edit
Here is how I'm looping in my Emberjs component. items is the name of the property after it gets passed into the component.
{{alerts-dashboard items=model}}
{{#each items}}
{{Totals.TotalUnreadNotifications}} // this outputs the number 5 as expected
{{#each NotificationData}}
{{NotificationId}} //this doesn't get outputted because the loop never happens
{{/each}}
{{/each}}
Why doesn't it work in Emberjs?
You need to use {{#each item in items}}.
{{#each item in items}}
{{item.Totals.TotalUnreadNotifications}}
{{#each item.NotificationData}}
{{NotificationId}}
{{/each}}
{{/each}}
I have created a JSBin example.
Edit:
Here is my edited JSBin showing that it also works if you use the lowercase name for notificationData, like mentioned in this related answer, that I have found here on SO.
{{#each model}}
<li>{{Totals.TotalUnreadNotifications}}</li>
<ul>
{{#each notificationData}}
<li>Type: {{NotificationType}}</li>
{{/each}}
</ul>
{{/each}}
I'm trying to list some posts with their related users. Each post has a title some text and a userId like this:
[{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
How can I relate my post model to the users model? It works like I tried it below but it's quick and dirty. Do I need to use backbone-relational? I just don't know if backbone-relation is an overkill for just one one-2-many relation in my application.
var fetchingPosts = BackboneApplication.request("post:entities");
var postsListLayout = new List.Layout();
$.when(fetchingPosts).done(function(posts){
$.each(posts.models, function(i, post){
var username = BackboneApplication.request("user:entity", post.get("userId"));
$.when(username).done(function(user){
post.set("name",user.get("name"));
});
});
var contactsListView = new List.Posts({
collection: posts
});
EDIT due to the question my post model looks like this:
Entities.Post = Backbone.Model.extend({
url : "url_to_rest_api",
idAttribute : 'id'
});
EDIT 2: Is this following parse function possible for the fact that I'm not able to change my rest api.
parse: function(response) {
user = BackboneApplication.request("user:entity", response.userId)
this.user = new User(user);
return response'
}
One option is to have your posts service return fully loaded "Post" models that look like:
[{
//not just an id anymore
"user": {"id":1, "username":"Fred", "email":"bob#bob.com"},
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
Then in your Post model's parse method you can do the following:
parse: function(response) {
//convert raw user json to backbone model
response.user = new User(response.user);
return response'
}
This avoids the relational dependency, but requires your rest endpoint to load user data with all post data. You could have your endpoints be specific but have your service layer be general so the concept of post and user are still loosely coupled
//pseudo
def getPost(id) {
def post = postService.getPost(id);
post.user = userService.getUser(post.userid)
render post as json
}