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});
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" } }
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 ?
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'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');
});
};
});
})();
});
});