MongoDB relations child to parent - javascript

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

Related

How to pass props to components in React js

I'm working on a project with React JS , and I want to pass a props to an array ,
This is the Component :
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class TaskItem extends Component {
render() {
const task = this.props.task;
return (
<tr>
<Link to={`/tasks/${task.id}`}>
{task.name}
</Link>
</tr>
);
}
}
export default TaskItem;
I want the value of {task.name} to be in the title of this array :
const todoDB = {
todos : [
{
//Proident tempor est nulla irure ad est
'id' : '561551bd7fe2ff461101c192',
'title' : ' ===> HERE <===' ,
'notes' : 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
'startDate': new Date(2018, 8, 3),
'dueDate' : new Date(2018, 8, 5),
'completed': false,
'starred' : false,
'important': false,
'deleted' : false,
'labels' : [1]
}
]
The array and the component are not in the same file
I hope those information enough to understand my problem, THANKS
you could convert the todoDB.todos array to a function ,pass the prop to the function and call it. sth like below:
const todoDB = {
todos: (props) => [{
'id': '561551bd7fe2ff461101c192',
'title': props,
'notes': 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
'startDate': new Date(2018, 8, 3),
'dueDate': new Date(2018, 8, 5),
'completed': false,
'starred': false,
'important': false,
'deleted': false,
'labels': [1]
}]
}
console.log(todoDB.todos("this is the title")[0].title)
I'm not entirely clear on your requirements but the following is a function that would generate an array of tasks in the format you provided.
const generateTodoDB = todos => ({
todos: todos.map(todo => ({
'id' : '561551bd7fe2ff461101c192',
'title' : todo.title,
'notes' : 'Id nulla ...',
'startDate': new Date(2018, 8, 3),
'dueDate' : new Date(2018, 8, 5),
'completed': false,
'starred' : false,
'important': false,
'deleted' : false,
'labels' : [1]
})
})
Now you just have to call the generateTodoDB function passing in an array of todos.
const myTodos = [{ title: "Get Milk" }, { title: "Get Bananas" }];
const todoDB = generateTodoDB(myTodos);
generateTodoDB is a so called arrow function. It automatically returns the result of its function because it's body is wrapped in parenthathese. The same is happening here with todos.map.
const fn1 = () => ({ thisObject: "gets returned" })
const fn2 = () => { return { thisObjectDoes: "not return automatically" } }

Filter one array based on property of another array

I do have 2 collections - events and bookings.
Events contain a collection of events. Bookings collection contain just the eventId of the event which we need to book and the current loggedin user.
I got the events which was not booked, using lodash
const results = _.differenceWith(
eventsArr,
bookingArr,
(event, booking) => event.id == booking.eventId
);
How do we select the booked events?
I was tying to filter the events array based on the eventID of the other array, but didnt work!
Any ideas will be of great help!
EDIT:
Adding the structure too, ( and thanks for the quick help, adding full structure of that can help another person, also the backend was firebase )
The events array
{
"-LWSkZgZ-e84Aq7EnvOo" : {
"date" : "January 17",
"description" : "Lorem ipsum dolor amet fashion axe cray pour-over green juice. Salvia everyday carry viral, PBR&B pop-up polaroid direct trade gochujang hot chicken disrupt gentrify quinoa crucifix pabst cred. ",
"imageUrl" : "https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
"location" : {
"lat" : 77.88,
"lng" : 66.65,
"name" : "Texas CA"
},
"name" : "MetalBone",
"ticketsAvailable" : true
},
"-LWSkbMLqDlpTgcgFHy2" : {
"date" : "January 18",
"description" : "Mlkshk brooklyn gastropub paleo bicycle rights. Man bun brunch helvetica food truck whatever tousled vegan vinyl pug cred mumblecore. ",
"imageUrl" : "https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
"location" : {
"lat" : 32.77,
"lng" : 96.7,
"name" : "Dallas SF"
},
"name" : "Big Day Out",
"ticketsAvailable" : true
},
The bookings array
{
"-LWdae8S33xrHfLetvT7" : {
"eventId" : "-LWSkZgZ-e84Aq7EnvOo",
"userMail" : "test#test.com"
},
"-LWdj2UDTwVV6_71Bcyd" : {
"eventId" : "-LWTraS93uC37S21syqP",
"userMail" : "test#test.com"
}
}
You can use _.intersectionWith() to find events/bookings with common id:
const results = _.intersectionWith(
eventsArr,
bookingArr,
(event, booking) => event.id === booking.eventId
);
This example takes, the data you've added, converts it to an array format, and uses _intersectionWith() to find booked events:
const events = {"-LWSkZgZ-e84Aq7EnvOo":{"date":"January 17","description":"Lorem ipsum dolor amet fashion axe cray pour-over green juice. Salvia everyday carry viral, PBR&B pop-up polaroid direct trade gochujang hot chicken disrupt gentrify quinoa crucifix pabst cred. ","imageUrl":"https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":77.88,"lng":66.65,"name":"Texas CA"},"name":"MetalBone","ticketsAvailable":true},"-LWSkbMLqDlpTgcgFHy2":{"date":"January 18","description":"Mlkshk brooklyn gastropub paleo bicycle rights. Man bun brunch helvetica food truck whatever tousled vegan vinyl pug cred mumblecore. ","imageUrl":"https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":32.77,"lng":96.7,"name":"Dallas SF"},"name":"Big Day Out","ticketsAvailable":true}}
const bookings = {"-LWdae8S33xrHfLetvT7":{"eventId":"-LWSkZgZ-e84Aq7EnvOo","userMail":"test#test.com"},"-LWdj2UDTwVV6_71Bcyd":{"eventId":"-LWTraS93uC37S21syqP","userMail":"test#test.com"}}
const result = _.intersectionWith(
_.map(events, (v, id) => ({ id, ...v })),
_.values(bookings),
(event, booking) => event.id == booking.eventId
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

How can I get the same object in the visitor area as I get in the admin area without the user $uid

Currently on a blog website like I got a problem I didn't expect when I start building it...
I build it like this:
• A admin area where you have to login where you can write/delete articles.
• A public area where you don't need to login where you can see the articles write in the admin area.
My database is build like below as you can see every user got a $uid. So because of how it's build my service look like this:
{
"articles" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORxrYnctixsx5sQ5DM" : {
"author" : "Zinedine Zidane",
"categories" : [ "Football", "Tennis" ],
"content" : "<p>Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.</p>",
"date" : 1539158014424,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41666967_311898482736538_5532086598150712503_n.jpg?alt=media&token=6b13fe37-357e-45db-8d0e-4436e166d359",
"name" : "Thalassio otium quem et hortaretur. \t"
},
"-LORy85GKdT9U9p_Iolk" : {
"author" : "David Kidouille",
"categories" : [ "Football", "ChatMignon" ],
"content" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"date" : 1539158086263,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/36981961_1869531810009121_4498273348232413184_n.jpg?alt=media&token=47fc2e67-d198-4533-8939-abc5d3dbed51",
"name" : "Omni habere atque perpetuae sic."
},
"-LOTQNaI7ry3WRavCjNt" : {
"author" : "Sophia Green",
"categories" : [ "Espresso", "Title" ],
"content" : "<p>Harum trium sententiarum nulli prorsus assentior. Nec enim illa prima vera est, ut, quem ad modum in se quisque sit, sic in amicum sit animatus. Quam multa enim, quae nostra causa numquam faceremus, facimus causa amicorum! precari ab indigno, supplicare, tum acerbius in aliquem invehi insectarique vehementius, quae in nostris rebus non satis honeste, in amicorum fiunt honestissime; multaeque res sunt in quibus de suis commodis viri boni multa detrahunt detrahique patiuntur, ut iis amici potius quam ipsi fruantur.</p><p>Ibi victu recreati et quiete, postquam abierat timor, vicos opulentos adorti equestrium adventu cohortium, quae casu propinquabant, nec resistere planitie porrecta conati digressi sunt retroque concedentes omne iuventutis robur relictum in sedibus acciverunt.</p><p>Non ergo erunt homines deliciis diffluentes audiendi, si quando de amicitia, quam nec usu nec ratione habent cognitam, disputabunt. Nam quis est, pro deorum fidem atque hominum! qui velit, ut neque diligat quemquam nec ipse ab ullo diligatur, circumfluere omnibus copiis atque in omnium rerum abundantia vivere? Haec enim est tyrannorum vita nimirum, in qua nulla fides, nulla caritas, nulla stabilis benevolentiae potest esse fiducia, omnia semper suspecta atque sollicita, nullus locus amicitiae.</p>",
"date" : 1539182528987,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/37112713_499156913858390_6321776699583234048_n.jpg?alt=media&token=dea02d84-dcc8-427e-92d1-92529499e052",
"name" : "Plerisque honoribus inventu in verae descendant quas in graves enim"
}
}
},
"contact" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"adress" : "Bla Bla Bla",
"email" : "michel#gmail.com",
"facebook" : "www.facebook.com",
"phone" : "0606060606"
}
},
"evenements" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORx0d49L5W1OHbaPkz" : {
"content" : "<p>Eodem tempore Serenianus ex duce, cuius ignavia populatam in Phoenice Celsen ante rettulimus, pulsatae maiestatis imperii reus iure postulatus ac lege, incertum qua potuit suffragatione absolvi, aperte convictus familiarem suum cum pileo, quo caput operiebat, incantato vetitis artibus ad templum misisse fatidicum, quaeritatum expresse an ei firmum portenderetur imperium, ut cupiebat, et cunctum.</p>",
"dateEnd" : "20/08/1995",
"dateStart" : "17/08/1995",
"name" : "Stand de tir au pigeon",
"place" : "33 rue de la Liberté, Bourgoin Jallieu"
}
}
},
"medias" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORymdySlsQ82_rZ6kk" : {
"description" : "Bla Bla Bla Bla",
"titre" : "30 ans de michel",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41466540_333985383837957_6494746608337518152_n.jpg?alt=media&token=079311d7-c42e-4e21-933e-36573e88a893"
},
"-LORyzf8ft5hS_MV_B10" : {
"description" : "klsjbvsjdkbvjkshd",
"titre" : "Bla Bla bla",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41532985_724838064517122_5880047170186967403_n.jpg?alt=media&token=86632def-47b3-4b30-84c9-c9af571da17d"
}
}
},
"sports" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORzZ2xq_JszbFaFyyn" : {
"description" : "<p>Nec vox accusatoris ulla licet subditicii in his malorum quaerebatur acervis ut saltem specie tenus crimina praescriptis legum committerentur, quod aliquotiens fecere principes saevi: sed quicquid Caesaris implacabilitati sedisset, id velut fas iusque perpensum confestim urgebatur impleri.</p>",
"handisport" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/42004027_2218122771593693_1511293494740179714_n.jpg?alt=media&token=430ddee9-a818-44ac-b80c-2483be38f1c0",
"name" : "Football",
"nbrPlayer" : 10,
"partTime" : 30
}
}
}
}
My Service in the Admin Area where I can access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
import { AuthService } from './auth.service';
export interface Article {
name: string,
author: string,
categories: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles/${this.uid}`).snapshotChanges()
.pipe(map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
))
.pipe(tap(next => {
this.store.set('articles', next);
})
);
constructor(
private store: Store,
private db: AngularFireDatabase,
private authService: AuthService
) {}
get uid() {
return this.authService.user.uid;
}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
addArticle(article: Article) {
return this.db.list(`articles/${this.uid}`).push(article);
}
updateArticle(key: string, article: Article) {
return this.db.object(`articles/${this.uid}/${key}`).update(article);
}
removeArticle(key: string) {
return this.db.list(`articles/${this.uid}`).remove(key);
}
}
My Service in the Admin Area where I can't access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles`).snapshotChanges()
.pipe(map(userId =>
userId.map(a => ({ ...a.payload.val() }))
)).pipe(tap(next => {
this.store.set('articles', next);
}));
constructor(
private store: Store,
private db: AngularFireDatabase
) {}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
}
So When I call the service for get my articles in the admin area I get and in the public area I get.
I find a way to get the value but with this way I lose the key object.
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
How can I get the same object in the visitor area as I get in the admin area ?

backbone marionette related models

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
}

jQuery, on hover show text snippet in another div

I'm trying to build an interactive banner that when you hover over the banner, you can hover over each image and see a snippet of text.
Im trying to make this snippet of text appear in my div titled 'textbox' only im struggling to make it change when the mouse leaves each image (you will have to see my fiddle for an example)
Let each image load BEFORE hovering over the html blue box...
http://jsfiddle.net/uEDBA/3/
jQuery
$(document).ready(function () {
$(function () {
var people = [{
id: 1,
name: 'Adam',
bio: 'This is Adam\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'justin.jpg'
}, {
id: 2,
name: 'Brian',
bio: 'This is Brian\' Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'chris.jpg'
}, {
id: 3,
name: 'Charlie',
bio: 'This is Charlie\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'sam.jpg'
},
];
w = 750;
h = 450;
var counter = 0;
(function nextFade() {
counter++;
var data = people[Math.floor(Math.random() * people.length)];
var figure = $('<figure style="float:left; width:150px; height:150px; background:red;" />');
var information = '<img src="http://www.placekitten.com/150/150" /><figcaption><h6>Meet ' + data.name + '</h6><p>' + data.bio + '</p>Read about ' + data.name + '. </figcaption>';
figure.html(information).appendTo('.interactive-banner-faces').hide().fadeIn(100, function () {
if (counter < 15) {
nextFade();
} else {
$('.interactive-banner-faces').children(':nth-child(12n+1), :nth-child(12n+2), :nth-child(12n+3)').addClass('rightTxt');
// On mouseover, fadeout the text overlay so we can play with the banner
$('.interactive-banner').on('mouseenter', function () {
$('.textbox').html(data.bio).fadeIn();
$('.overlay').stop().animate({
'top': '-450px'
}, 200, 'easeInCirc');
}).on('mouseleave', function () {
$('.textbox').html('').fadeOut();
$('.overlay').stop().animate({
'top': '0'
}, 600, 'easeOutCirc');
});
};
});
})();
});
});

Categories