A Voyage AI se une ao MongoDB para impulsionar aplicativos de AI mais precisos e confiáveis no Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Desenvolvedor do MongoDB
Centro de desenvolvedores do MongoDB
chevron-right
Produtos
chevron-right
MongoDB
chevron-right

Construindo um aplicativo da Web em tempo real com os serviços de aplicativos do MongoDB Atlas

65 min. – Publicado 22 julho, 2023
MongoDB
Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Vídeo
star-empty
star-empty
star-empty
star-empty
star-empty
Pesquisar
00:00:00Introdução
The veudeo begeuns weuth an euntroducteuon to the sesseuon, outleuneung the goal to create a real-teume web appleucateuon useung MongoDB Atlas and Atlas App Serveuces.
00:02:18Configurando o MongoDB Atlas
The presenter walks through setteung up a MongoDB Atlas cluster, leunkeung eut to Atlas App Serveuces, and confeugureung data access and authenteucateuon.
00:14:06Implementando lógica de negócios
The sesseuon conteunues weuth the eumplementateuon of buseuness logeuc eun the web appleucateuon, euncludeung fetcheung and deusplayeung aucteuon data from the database.
00:27:34funcionalidade em tempo real com Change Streams
The focus sheufts to addeung real-teume functeuonaleuty useung MongoDB change streams, wheuch push updates to the cleuent weuthout the need for page refreshes.
00:39:17Fechando conexões HTTP
The eumportance of closeung HTTP connecteuons when naveugateung away from pages eus deuscussed, and the presenter demonstrates how to properly handle theus eun the appleucateuon.
00:44:06Perguntas e respostas e conclusão
The sesseuon concludes weuth a P&A segment, where the presenter answers questeuons from the audeuence and proveudes addeuteuonal eunseughts eunto the appleucateuon 's development process. The feunal secteuon wraps up the deuscusseuon and heughleughts the next steps for veuewers eunterested eun learneung more about MongoDB and real-teume appleucateuons.
O foco principal do vídeo é demonstrar como criar um aplicativo web em tempo real usando o MongoDB Atlas e o Atlas App Services, enfatizando a eficiência de custos e as atualizações de dados em tempo real.
} Pontos-chave
  • O aplicativo é criado usando o MongoDB Atlas, Atlas App Services e a biblioteca da Web do Realm.
  • O backend está configurado para ser econômico, usando as camadas gratuitas do MongoDB para serviços de nuvem.
  • A funcionalidade em tempo real é obtida por meio de change streams do MongoDB, permitindo atualizações sem atualizações de página.
  • A sessão aborda a configuração da autenticação, as regras de acesso a dados e a conexão do frontend ao backend.
  • É destacada a importância de fechar conexões HTTP ao navegar para fora das páginas.
Todos os vídeos do MongoDB

Transcrição completa do vídeo
[Music] thank you [Music] [Music] foreign [Music] thank you [Music] foreign [Music] [Music] hello everybody Welcome in to this session of learning with loose it is Friday the 21st of July God that's this year's going quickly how how is everybody where is everyone watching from so I am in Manchester in the UK and I am pleased to say that on today's learning to lose I am joined by my work bestie travel buddy and all-round Tech expert uh Mira so mirajax introduce yourself to everybody that's watching sure Hi listen thank you for having me today my name is or for short Mira I'm from Bulgaria currently I am in the on the Bulgarian Seaside but I don't tell my manager that because I'm still working or supposed to be working so I'm proving that I'm working today with this live stream uh Lucy and I joined mongodb about two years ago or like almost like almost two years ago for me and two years ago and one month for her and we were both on the same team we are now still working for developer relations in slightly different teams but yeah she has been my work bestie ever since I joined so I'm very very excited about this yeah me me too it's always always fun when we get together whether it's in person or in a live stream I see we've got people from all over we've got uh wow we've got India Peru Austria Kenya Malawi uh different places in the US especially New York Tanzania wow we've got really good um good mix Sri Lanka Panama amazing it's really great to see people from so many different uh parts parts of the world we are you know we're Global people we like to travel so it's always fun when uh our friends join us from around the world so do you want to tell everyone a little bit about what we're doing today I saw there's a couple of questions in chat about the tech stack we're using because the title isn't a giveaway yep uh so today we're building a real-time web app and more specifically we are building an angular app we won't be building DUI sadly but we will be building the business logic of the application the database and also the back end for the backend we'll be using um a low code backend which is mongodb atlas app services and you will see how all that works uh I will start sharing so that we can yeah so yeah we will be using mongodb and mongodb Atlas clearly for the database and the back ends and for the user interface we'll be using angular um so generic typescript JavaScript so you don't have to have knowledge about JavaScript and typescript to follow along though we'll be also using the mongodb query API and the aggregation framework to make some um yeah some requests to our database and fetch the data that we need and to open change streams which are quite important for for what we're building today the real time functionality and it's good yeah yeah I said sorry I was just going to say it's a good job that you don't need to know angular because well I mean you and I joke about this we have done for years if you've watched this street live streams before you might know I always joke about JavaScript because it's just the thing that you can't live without but I don't understand a bit like CSS um I've done a bit of react um and we keep talking about names do angular so maybe at some point we should we should just do like angular 101 together on a live stream and add Atlas into it but uh yeah there's not too much knowledge needed uh yeah so it's exciting and I like that we're using such a breadth of of like mongodb Atlas like products and stuff today that's always good indeed yeah I always jog the thing your worry is more um close to C sharp than it is to JavaScript so um yeah we'll be right at home here if you are coming from java background yeah so uh so of interest it's real real-time bidding app what do you mean by real time uh that is a really good question I don't know how you knew to ask that question maybe because I showed you the slides before but yeah the first yeah the first question that we need to answer today is what is real time uh and real time can mean many different things because it's a very like non-descriptive term honestly uh so I stole this slides from our amazing co-worker here at mongodb Kenny Gorman uh yeah and so he explains it really well on this slide so uh for some people in the development world real time might mean microseconds so if you are building a system for car brakes for the automobile industry um activating the brakes uh before impact means that it's this is something that should happen in less than a second in in a hundred microseconds or even less it's a very time sensitive for this operation to be to be as quick as possible and here it's even it even this even means that in order for the um for the operation to for the function to be um with a successful outcome to be working uh it should meet this specific threshold so anything outside of the threshold makes the function not working properly means that it's running again correctly and when we're talking about web apps we are actually talking more about relaxed real-time uh not the strict real time we're talking about uh having um receiving the data and it is available without needing to do page refresh uh and in this case the threshold can be milliseconds or even seconds so we have a much lower sensitivity to latency and again today in our web app scenario we'll be talking about relaxed real-time however you can use mongodb and you can use Atlas to implement a strict real-time event delivery as well in fact we recently announced a very interesting or very important functionality related to streaming we're all going to discuss it today about stream processing but if you're interested in strict real-time make sure to check out the latest announcements that we made at our annual New York conference mongodb dot local NY see oh yeah so back to web apps uh what is what is what does it mean to have a real-time data delivery in a web app well what people understand by by real time is the server pushing data to the client which means that we don't need to refresh the browser page to receive new information and examples for that are text chat a stocks tracker in-app notifications and also online auctions in all of these examples we are not expecting the application to to need a page refresh in order to um to receive the new information uh coming from the server right so when we are chatting with someone we see the text messages as they come in we don't need to refresh the whole application uh if we are using a stocks tracker application we see the price as it changes over time in maybe every second or even um whatever an interval we said we don't need to refresh the page to see the updates in-app notifications clearly we don't need to refresh the app to receive a notification it arrives from the server using different mechanisms online options uh so at this point I'm going to show the application that we're building today because not every person is familiar with online auctions I personally never used one to be fair but it is a good and like kind of a more non-traditional example to build I don't want to build a text chat or a stocks tracker for this because it's it's kind of mainstream to do it so we are going to be building on the auctions a bidding system auction system or bidding system so what do we have here we are going to be bidding for cars uh because why not and for no particular reason at all I'm gonna go to the Tesla Model 3. and the bidding what happens here so I'm gonna click this button plus 10 and um we are gonna see this price update so we see the price update in real time if there are other people on the page uh we will see them bidding as well this is a live application um yeah we can send you the link to this in the chat you can play with it throughout the stream uh you can look at it here or we're also gonna share it in the chat uh but yeah you can play with it try to break it I'm sure you're smart smart people you can break it yeah people started connecting and updating the price uh this is basically real time uh delivery in our application in our web app let's go back to the apps list to the cars list so if people update something here let's simulate that by switching Off full screen opening a second browser and going to let's go to this car all right again for no particular reason at all I'm opening this car maybe it's because I drive one of these and you see here that it doesn't matter on which page I am this is the cars list and this is the cars Details page we see the updates everywhere oh that's cool yeah so we are connected everywhere to the underlying connection collection and we receive the uh the changes to the price as they as they happen that's really quick as well which I don't know why it always surprises me how quick these things can be yeah and this cluster is deployed in Europe so uh if we want to make it quicker for everyone around the globe we can use also Global deployments in app services or um yeah we will need to use the global performance for our backends in-app services but even even I I presented this um this demo as a talk in India and my cluster was still in Europe and the delay was super minimal it was like under 100 milliseconds um and yeah you can you can play with all that um you have the the link in the chat uh and the final functionality that we're going to implement today as well so we're going to implement all that uh the final functionality is full text search so here if I look for Tesla I have a full text search with autocomplete and I can look for Ferrari and I have all these cars if I look for spider I see again um yeah all these cars we can also Implement fuzzy search so if I make a mistake here mistype something we should see the results but I haven't implemented full text search if we have some time we can do it it's just a single parameter that they can use to implement that using catwa search which is another service available in mongodb Atlas nice yep it's pretty cool so this is the app that we're going to be building today uh let's go do we have the link for the folks in can we send it again I see that some people yeah so this is the link to the app itself I was going to share the link to the uh GitHub repo shortly someone's asked about that um we can either share it now where we can share it later I wasn't doing yeah straight away if you didn't want to share it now all right I have it over here in my favorites here I can send it to you and you can share it with everyone okay um but yeah this is a repository it's public you can play with it uh in fact if you have an Atmos cluster it will be easier to follow along but uh there is still time to create one and follow along so if you follow want to follow along go to the live coding branch and clone the repo um and yeah I've actually made some changes today to make it easier and quicker for us to finish this in an hour so yeah the live coding branch and the main branches the production version that I have deployed the app is deployed on Firebase it doesn't really matter where you deploy it though so you can you can deploy it all right um let's go back to our slides where are my slides okay they're here okay so these are the examples of real-time apps we're building the last one the online option everyone good everyone clear you can't answer so yeah if anyone's got any questions as we go along please feel free to ask them all we do request is that questions are relevant to the topic if you've got any non-relevant mongodb questions or Community forums are the perfect place to ask them because then everyone can answer and benefit from the answer publicly um obviously we've only got a certain amount of time today so as much as we love a good ask me anything we don't have time for that but of course if you've got any questions about this topic as we go along in the code and the app and you know real-time apps by by all means ask away and we'll cover them awesome that's great all right so let's make this a little bit more interactive in web apps there are four main strategies to implement real-time server pro events these are short polling long polling web sockets and servers and events in the next four slides I'm going to show you a diagram for each of these without telling you which technique I'm using and you will have to guess which technique I'm using all right first one so we have the client on the left the server on the right the client sends a request the client in this case is our browser the client sends a request the server Waits until there is new data available and when there is new data available the server responds then the client does whatever it needs to do with that data probably display it in the UI or whatever it needs to do and it sends a request again or almost immediately the server again waits for new data and when it's available it responds which technique is that is it short polling long polling server sent events or websockets you can write your your guesses in the chat in LinkedIn or we are also streaming on YouTube I know there is like a slight delay with the stream and what you guys see if you're watching so we're gonna wait for 10 to 15 seconds to see your answers yeah get your answer soon I could cheat because I know the answer but I'm not going to it's we're we're here to learn together and since I know the answer it's time for others to chime in what do we think what is Diego saying I can't read the whole comment the full comment uh he's he's having a discussion with somebody about Ai and programming hahaha but uh what how obviously hi to everybody but uh hi Diego Diego is one of our uh Gabrielle colleagues so it's always very exciting when we see our colleagues in trap everyone knows Diego you don't need to understand that's true sorry all right so this is a technique called long falling because we are waiting for new data before we uh respond before the server responds uh the second Technique we have a request the server responds immediately it doesn't matter if there is new data available or not if there is no data the server sends the new data if there is no new data the server sends no new data says no Then the client waits for a certain threshold maybe 500 milliseconds usually it's um it's less than that and the client sends another request the server responds immediately the client Waits again and this is repeated over time multiple times every second as you can see here there is some some problems where overloading the network with a lot of traffic and I'm gonna wait for your answers again uh yeah I actually see the answer is coming coming up uh which of the three techniques that are left is this is it short polling websockets or server sent events people are already replying yeah we've had lots of different answers so far which is always good means it's good to be and I see that Diego is leading his side side quests discussion you've got quite a few for short polling some for long polling a couple of web sockets all right so this is short polling uh because we are not waiting for any new data we're always responding that's why it's called short polling the next technique is quite different we are working with a TCP connection uh that is open all the time first we start with the handshake over HTTP so we do the handshake the client sends a request for a handshake the server response the connection is established and the tsp connection is actually um running the whole time as I said and it's a full duplex collection this means that the client can send events to the server and the server the server can also send events to the client uh both both sides can communicate with each other and finally any of the sides can close the connection so this is either websockets or server sent events and yeah people say web sockets and they're correct these are web sockets again TCP connection the most important angle the answers yeah a lot of smart people here finally uh this as you may have guessed This Server sent events because it's the only one left but how does it work so the client opens an event stream uh which is basically a simple long-lived HTTP connection so we don't need a separate protocol a TCP connection or something more sophisticated to work with server sent events it is a simple HTTP connection and so the other big differences here that is that the server can only send um send events to the client it's a Simplex communication it's not full duplex and finally the client can close the HTTP connection and this is server sentence server sentence is slightly older than websockets actually and they both have their applications so this is a comparison of the two We're Not Gonna discuss short pouring and long polling uh they're super easy to implement but they're not very practical nowadays I mean of course if you're building like a simple demo or just a proof of concept you can you can do it with short polling uh it there is not a problem but in real world production applications maybe it's better to use one of these too all right just uh just in the comment someone's saying that I don't uh they're saying that the video is not live looks like it keeps restarting some chunks not sure if it's uh buffering for them but no it's absolutely live yeah sorry guys if uh if it's buffering for you it's probably the streaming platform uh either LinkedIn or YouTube or um the connection but don't worry uh the recording will be available afterwards so you can always watch this um afterwards as well uh also you can play back certain moments all right back to to the topic so web sockets for the play servers and events Simplex only the server can send events websockets use the websocket protocol that opens the TCP connection servers and events use a simple long-lift HTTP connection websockets can send binary and utf-8 data and service and events can can send only utf-8 the problem with websockets sometimes is that certain firewalls block the port where you need to open TCP connections on so websockets can be blocked by some corporate firewalls um or firewalls in general doesn't need to be corporate uh and server sent events there is no such problem because it's a simple HTTP connection you can't I mean if you're blocking any website then your blocking servers and events as well but that's not what firewalls typically do uh and yeah again they have their benefits and um and disadvantages as well in terms of support websockets are supported pretty much everywhere uh not in IE 69 and not in Opera Mini but nobody cares about this anyway the global support meaning the support of every single browser that is being used today is 98.36 so you can use them server sent events are also not supported in IE 11 and if you still care about i11 I'm terribly sorry um for you but the global Sports is again over 95 so uh yeah you can use both both of them a quick spoiler Awards uh the the library that we're going to be using is called rayon web which is a library maintained by the mongodb team here we have a whole engineering team maintaining this Library this Library uses server sent events so we can only receive data from the server and you will see why it makes a lot of sense to be using server sent events in this Library all right I showed you the application uh this is again a QR code and the URL for the application if you still don't have it if or if you're joining right now uh you can get it uh Diego also share the link in the comments so you can visit it there as well and I can pop the link into YouTube as well yep all right it's a very simple application as you saw so we're gonna set some restrictions some objectives that we need to meet in order to to make it more interesting so first we want it to be cost effective effective in fact I don't want to be spending any money on these applications today I want to take advantage of all the free cloud services out there free is the best yeah second I want to have real time uh delivery of events so I don't need a page refresh I want to see everything as it's as it happens and finally we want to have autocomplete search and we're going to implement all these three things today let's get started so how do we make it cost effective uh we're going to be using Mong DB Atlas uh if you register for modib Atlas which is mongodbase developer data platform you will get one free Cloud cluster that you can deploy in one of the three major Cloud providers Google Cloud AWS or Azure and you get half a gigabyte of storage so it's more than enough for our simple application it's more than enough for any options app honestly unless you're storing like I don't know videos of the options which you shouldn't be storing in your database anyway um half a gigabyte of storage is quite quite fine honestly I mean if you have millions of auctions maybe don't store them in our operational database maybe archive them you're not using all of them so uh yeah it's kind of enough and that's what we're using today so the database is handled it will be for free if you register for Atlas and deploy a free course store it will be free for you as well for the backend we'll be using atos App Services which are again a low code backend solution you get one million free requests per month and 10 000 concurrent requests as well so I don't think we have 10 000 people on the stream so we are safe uh you can all connect and use the app all right let's go to the demo yep all right so this is our database cluster I already deployed it uh just to quickly show you if you want to deploy a new one and if you want it to be free I need to go here to shared and select m0 so this is the cluster Theory it should be m0 and you can use whichever cloud provider you want in order yeah the best one I was just gonna say Normal reviews who is a Microsoft MVP I'm using uh Microsoft Azure today um and yeah it's fine Azure is fine great all right so for sure however you want to say it yeah so this is our database cluster it's using mongodb6 um or eight it's deployed in Azure in the Netherlands because we're both based in Europe we're using cam0 the free coaster tier and what else yeah we're gonna link app services and we're gonna create an apple search index but first let's take a look at the data that they have here so we have a single database called auctions I'm going to zoom in a little bit and a single collection called cars and in this collection we have only 14 records these are our cars auctions and this is how a document looks like so we have the name of the car an image URL I'm using a CDN so you'll see just the final bit of the of the image we have the current bidder which is a node generated username every time you refresh the app you get a random username and the current bit and also the end date for the auction so that we know where the bidding stops and again we have a bunch of these cars uh if we take a look at the particular one we have different eight dates we can change this if we wanted to if to update the database in line uh but don't do that in production all right so this is our database free nice awesome next is our backends for the backend I need to go to the app Services tab here at the top and I will be using again a library a client library to connect from from my web app to this um to this backend so how do we create this backend here I'm going to start from scratch uh you have different templates that you can use I always start from scratch honestly it's super simple to set up so we might as well do it we have some application guides if you want to learn how to set up graphql or triggers or use the web SDK which is something that we'll be using here you can you can take a look at the application guides as well again it's free to deploy this app service there is a generous free tier per month as well so make sure to utilize it so the first thing that they want to show you here is the do you guys see the screen okay yeah I think it's it's fine it's zoomed in enough I want to show you the linked data sources under under manage so by default because we have just a single database cluster in our project it is linked so you can see here this is the name of my project learning with lose real-time web apps and this is the name of the database cluster auctionary and it is linked to the data source and the name the default name is mongodb atlas we will be referring to our database cluster with this name from now on mongodb so when we need to communicate to the database we'll be saying mongodb Atlas you can change this name if you want to it's it's just the default and I'm Gonna Keep It next thing we want to set up is Authentication so I'm going to go to data access and Authentication Atmos offers a bunch of different providers we have email passwords we have social login API Keys Json web tokens or you can even execute your own custom logic to authenticate users because I want the website to be available to everyone and I don't need your credentials I'm going to enable Anonymous login and when I enable this and save the draft I'm going to zoom out so you can see what's going on when I save the draft I I get um kind of on state unstaged changes in my application so we are not directly modifying uh the production application if we're if someone is actually using this in production we're not modifying it immediately we are creating a new draft and now I can go to this Banner here review the draft uh you can see that this is actually a Json file with our configuration so we have secrets providers we enabled Anonymous user and yeah we have some other settings so you can actually keep all of these files under Source control app Services also has an integration with GitHub so you can sync your GitHub repository with your application State here in the user interface it's it works very well so check it out um if you actually want to use this in your day-to-day development so I'm gonna know so I've got a quick question from somebody if you've got a second yeah sure uh so we're being asked is there any monitoring like dynatories to check the latency so I think that was referring to uh yes the actual app itself yeah so you can go to logs if I see logs okay the locks are over here at the bottom again under manage and I still haven't used the app but here you can see the latency and um also like the request and everything the person who's requesting it I think you can do forwarding stuff like that uh we're we're gonna go back to this page when we start using the application and I'm gonna show you actually I can also show you my production app Services application I have it somewhere over here so just so we don't have to go back again I'm gonna show you my production application for auctions so here I have a function open because I want to show you something later but if I go to logs I see all the logs and how much every request took nice so spoiler Awards because we open a change stream which is an open request an open long lived HTTP connection this takes 15 seconds so it kind of takes until I refresh the page and then it's it's closed um all of these chain streams these connections are multiplexed on the back ends automatically by app services so we're not actually opening 100 connections um with every refresh of the page for every user we have only one chain stream open pair collection in the database and in our example we only have a single database for the cars um sorry the a single collection the cars collection so we are on the backend app Services is opening just a single change stream but we'll get to that later again if you expand the details here you can see a lot more details about the actual connection the IP address of someone um what's what happens how many documents are matching and and so on but yeah you can check the latency if you if you want and yeah if I were to deploy this to the I don't know us West one I would see a much bigger runtime yes just because we're further away just to clarify it's not because Us East one is any slower it's just uh yeah we're further away yeah and you're gonna see that in any cloud provider it's just the distance unless you have a globally distributed CDN or a globally distributed application you're gonna see that latency in any cloud provider all right um back to our application I have set up Anonymous authentication and then I'm gonna set up some rules so these are data access rules I am going to pretend I know what I'm talking about and close the helper window and I'm gonna go straight to my cluster this is the service uh the auctions Database The Cars collection and here I can set up the rows so we have some popular presets uh deny all access so no one can do anything with the collection then we also have read oh everyone can read everything in the collection they can also use Alpha search with it but no one can update or insert new documents oh well I mean I can do it from the database but not from the backend and finally we have read and write also everyone can read and rewrite all Fields I don't know why these are popular presets because I wouldn't use any of these in a production application so I'm going to start from scratch I'm sorry I'm being a little bit um incorrect here yes okay you're being security conscious it's okay security conscious uh that's what John Page taught me to do um uh let's let's create a new row I'm gonna call this row reads oh everyone can read all the fields I don't have anything Secret in my collection and write bits so I want people to be able to update only the bits fields and the current bitter fields and I'm gonna enable auto search because we're gonna use it later and I'm gonna specify field level permissions so helpful yep for these specific Fields current bit and currents bidder I will enable read and write and for everything else I'm going to enable read and this is yeah this is fine I mean they're like certain issues with that because anyone can write whatever they want in current bit and current bidder but we will fix that later or if we don't have time for that I will tell you how you can fix it all right we're gonna save the draft uh deploy again you see again we modified something called rules.json and this is everything this is our backend it's everything we need for now again there there are a lot of things that you can restrict here and fix um but this is good for now here yep yep um zoom in a little bit more I'm gonna go back to the home page and I'm gonna copy the A app ID I'm going to use this app ID to connect from my application from my web application so this is my web application running in localhost you can see that all the user interface is implemented but the business logic is not there so we're gonna implement the business logic if I search for anything I'm going to see just fake data if I go over here I'm gonna see again just placeholders so we're going to implement all that by connecting to this back end that we just created people are still updating the real application go for it it's it must be fun uh let's get this one all right so this is the application Jaguar application that I have running locally I'm gonna go over here and I have some of the logic implemented but let's go through it so I have a special service which is just a typescript class really that's angular takes care of connecting to the actual application but this service is going to connect to my backends again I'm using a library called realm web a library maintained by the mongodb team and this is the library that can connect to AdWords app services to our backends um I have a static um member fields I I always forget what's the right one in typescript and compared to c-sharp and other uh we have a studying Fields here in the class and we are instantiating this has a Singleton so if we don't already have this app we are gonna call new realm app and we need to provide the app ID right this is the app ID I'm going to save this and then after we creates we instantiate the app we also create Anonymous credentials and finally we call app.login using disk credentials and if the app is already instantiated we are just gonna return it that's that's everything that happens in this class all right so now I'm gonna move to the auctions service which is the business Logic for our application for the auctions so the details page the list the bidding everything and we're going to start implementing some stuff the first thing I need to implement is get collection I'm gonna get the collection from this realm app service the real map service is injected using dependency injection into the class into the this service uh so let's grab the local variable Rail map service and I need to call GitHub instance which is the method that we just implemented this is an async method so I need to await it and I'estou vai atribuir isso a um aplicativo de código variável local agora dentro deste aplicativo posso obter o cliente MongoDB, então preciso obter o usuário atual e então preciso obter o cliente [ __ ] novamente o nome do serviço mongdb Dash Atlas agora do cliente posso obter acesso à coleção preciso Go para clientes.database os bancos de dados leilões e a coleção é chamada carros tudo bem usei find para devolver a coleção mas você vê que estou usando esses pontos de interrogação em todos os lugares, se você não estiver familiarizado com essa sintaxe, é uma sintaxe relativamente nova no script Echo em JavaScript e se essa coisa não for um objeto ou estiver indefinida ou não for a expressão inteira em vez de lançar um erro, a expressão inteira será avaliada como não e como estou usando esses pontos de interrogação em todos os lugares da coleção, pode haver não, então preciso verificar se há algum tratamento de erros aqui da forma responsável sim, então vamos lançar um novo erro e apenas dizer que uh falha ao conectar ao servidor e algo genérico assim, eu realmente não gostaria que o usuário dissesse o motivo pelo qual o aplicativo não está funcionando um, eu tentaria mudar isso porque não sabe tudo bem, então temos nossa coleção e a primeira coisa que vamos implementar que é realmente real está carregando um opções então onde estou usando isso nesta página aqui oh este é o aplicativo ativo Não preciso mais dele uh onde está o host local tudo bem então carregar um leilões é aqui é esta página a página com leilões de áudio então, quando eu implementar a função, ela deve ser vinculada aos componentes Angular que exibem a interface do usuário uh o componente Angular obterá os dados da lógica de negócios do serviço e exibirá todas as opções tudo bem, então Go lá, temos cargas, e removeremos a implementação falsa. o pipeline de agregação ine pode ter vários estágios e cada um desses estágios pode transformar os dados, então é um pipeline para Transformações e estou fazendo apenas algumas Transformações aqui.Quero classificar os dados pelo estado final para que eu possa ver o opções que terminam primeiro no topo e o segundo estágio que usarei é o limite inferior, então vamos limitar a, vamos usar esses argumentos passados para o método, vamos limitar a 10 por padrão, vamos salvar isso Go para a atualização do aplicativo está funcionando sim, está funcionando e vemos todos os carros para provar que isso é real Vamos definir isso como quatro, Go Atualizar [Música] e temos apenas quatro carros, então depois disso nós precisa de um uh como um confete ou um efeito de Som de comemore Eu posso sim, você pode reproduzir isso, então fizemos uma pergunta sobre qual linguagem é essa, então isso é Typescript correto, sim, uh, por ser Angular parece muito com c -sharp mas sim, é Typescript um. Eu espero que você possa acompanhar não há nada Typescript speci fic então os scripts essencialmente permitem que você adicione definições de tipo para as coisas que você está definindo então aqui nós temos qualquer então pode ser qualquer coisa nós temos uma opção de consumidor em tipos de JavaScript , como número da string , e esse padrão é um uh sim, esse é o Typescript também algo que o Typescript nos fornece, também podemos usá-lo em JavaScript , mas com o polyfio é um gravador que, novamente, se você vier do Java c-sharp ou você ele provavelmente está familiarizado com gravadores e este é um gravador de Angular e injetado significa que este é um serviço que será fornecido no módulo Raízes de Angular , tudo bem, então implementamos limites de uma carga, lamento, apenas vamos definir isso de volta para limitar só não vemos isso um único aviso aqui e Go implementar encontrar um, encontrar um, uh, essencialmente, consegue um único leilões, então se eu for a esta página, você pode ver aqui no URL que estamos passando o ID do objeto, então estamos vai usar isso o ID de bject para resolver o documento do banco de dados e exibi-lo no MongoDB, você precisa ter uma chave primária e ela deve ser o campo de ID de sublinhado, mas é claro que você também pode ter outros identificadores para que possa ter seus próprios identificadores que você não tem não é necessário passar IDs de objetos no URL , ele pode ser um pouco como um padrão de lançamento também para fazer isso em muitos casos, então sim, aceite isso como um curte, talvez considere isso antes de fazer isso em seu aplicativo nem sempre é ótimo ideia uh, mas nós, neste caso, vamos usá-lo é super simples, então vamos obter uh isso a partir da URL , o componente Angular passará para o serviço e vamos usá-lo para conectar o banco de dados e encontrar o documento que estamos procurando e este é o ID aqui, então preciso da coleção de novo. Vou copiar a coleção, então temos a coleção e, desta vez, chamarei coleção de ponto, encontre um e procurar para ID de sublinhado, a chave primária deve corresponder a esse ID , mas é meio explícito e aqui eu escrevi isso pode ser qualquer um de novo como qualquer um no Typescript não é algo que você deva fazer em geral, mas eles quiseram deixar explícito aqui que você não deve confiar em seus usuários então qualquer pessoa pode chamar esse método a partir dos componentes, uh, praticamente, eles podem modificá-lo e chamar o método e o ID pode ser qualquer coisa, então precisamos tentar convertê-lo em um ID de objeto que é um tipo MongoDB especial bem tipo BSON mas o MongoDB usa bison para armazenar documentos e ID de objeto é o que usamos para armazenar chaves primárias, então vamos converter ou tentar converter esse ID em um ID de objeto, então o ID deve ser o novo ID de objeto e se recebermos um erro, na verdade, não vamos fazer nada aqui, podemos Implementar alguns como tratamento de erros e podemos desenhar um novo erro apenas para ver algo na célula para converter ID de Conforto algo como inespecífico, mas sim, não deveria estar mostrando isso aos seus usuários sim, tenha cuidado com essa mensagem de erro t realmente não jogaria um erro no é o caso, mas sim, se tivermos um problema com a nossa implementação, queremos ver isso no console, tudo bem e, finalmente, sim, estamos apenas passando o ID , que agora é um ID de objeto, espero salvar isso Go de volta ao aplicativo e atualize e temos o Lamborghini Aventador Não faço ideia de como se pronuncia uh você fez um Lamborghini Aventador sim Aventador sim, é Aventador páginaQuero ver esse preço mudar, então vamos Go em frente e faça issoNão vamos entediá-los com mais codificação ao vivo por enquanto, então oh, estamos funcionando muito rápido aqui estamos em 50 minutos, então o que eu estou fazendo aqui eu tenho o nome de usuário o nome de usuário é b habilitou, então não queremos ver dados aleatórios chegando em minhas webs de produção semelhantes ites com xingamentos e coisas do tipo, então estou verificando se é um xingamento que me recuso a fazer qualquer coisa, então obtenho a coleção e uso a atualização um para aumentar o bit, então encontro a opção com esse ID desse lance atual e este bit atual e incremento os bits atuais com o número específico que as pessoas usaram Defino o nome de usuário para o nome de usuário atual e é isso que é tudo que estou usando para salvar isso Go aqui para a atualização do aplicativo apenas por caso e eu seja vai aumentar com 100, não vemos a atualização em tempo real ainda, mas quando eu atualizar você vê que é 360. então Post 10 deve ser 370. 100 2 tudo bem, então uh Go falar sobre as coisas em tempo real. não queremos mostrar esse vídeo corretamente, então implementamos a redução de custos, mas e o tempo real que precisamos usar um serviço de nuvem gerenciado, mas não precisamos, mas neste caso vamos usar como gerenciar o serviço de nuvem o máximo a escolha popular seria o upsync Amazon Web Services uh segunda opção popular seriam as nuvens confluentes e, neste caso, vamos usar o MongoDB Atlas porque tudo o que estamos fazendo agora está no Atlas , não faz sentido Go para outro plataforma, mais especificamente, vamos usar change streams do MongoDB que você pode usar cadeias de fluxos fora do Atlas eles estão no banco de dados principal, são eventos que vêm diretamente do registro de operações do banco de dados e nos permitem acompanhar as alterações de dados em tempo real à medida que elas acontecem em tempo real como em uma forma mais relaxada a qualquer momento, Go começar a usá-los uh os fluxos de cadeia podem ser abertos uh por meio dessa biblioteca que estamos usando realm web e este será o nosso backend garantirá que o observador correto o fluxo de cadeia correto seja aberto na coleção então como vamos fazer isso, temos uma lista de ideias porque não gostaria de abrir a tela de cadeia para todos os itens da minha ID . tipo de dados especial do MongoDB não é para o campo de ID de sublinhado bonito sim, é um tipo BSON um sim um na coleção e, finalmente, eu obter um gerador não Go entrar em detalhes sobre geradores agora, mas principalmente se eu chamar collection.watch o backend abrirá e mudará o fluxo ele também abrirá um evento enviado do servidor como se fosse abrir uma conexão HTTP de longa duração que nos permitirá obter eventos do servidor e para assistir a isso deve ser um objeto e não um array para assistir.Quero assistir apenas esses ide como aqui, uh, o gerador assíncrono produzirá um resultado toda vez que os dados chegarem da rede para que eu possa converter isso um gerador de sincronização em um observável um observável rxjs e me inscrevi para esse observável em meu componente Vou aplicar algumas transformações para o observável primeiro, vamos filtrar e obter apenas os eventos de atualização são os eventos de atualização um e, em seguida, vamos extrair apenas os dados de que eles precisam, então obterei apenas o ID do sublinhado, que é um evento que considero que foi chave de documento ID de sublinhado e vamos pegar a descrição da atualização que está em eventos.descrição da atualização, vemos que temos uma ordem bonita e completa aqui, vinda do Typescript e das digitações que a biblioteca da Web RAM tem, então vamos salvar isso e ver se nós tem coisas em tempo real o aplicativo é atualizado veja se nós essa é uma pergunta sim, funciona palavras Spoiler que funciona Não estou surpreendente que eu tinha tudo o que o prêmios Spoiler é que temos problemas com esta implementação um, um, eu estou Go os problemas realmente q rapidamente e talvez deixemos a pesquisa de texto completo para outra hora porque temos apenas alguns minutos restantes, mas é importante mencionar esse problema, na verdade, então vamos atualizar a página e o que vamos ver o que acontece aqui na guia de rede então quando eu atualizar o preço, eu executo uma atualização típica do preço e esta é a conexão HTTP de longa duração que vemos a solicitação ainda não estar concluída, o que é de se esperar, mas quando eu Go desta página, gostaria que essa solicitação terminasse e como faço fechamos isso tudo bem e aqui abrimos que, na verdade, outra conexão do Watcher porque estamos observando mudanças nesta página também esta é a conexão do Watcher e, se eu ver a anterior, ela também não terminou, o que é muito ruim para nós HTTP Nós implementamos um operador rxjs especial do evento de alteração, Go para sua definição e, quando cancelamos a assinatura do observável, chamamos de fonte dot return, a fonte é o assíncrono gerador e quando dissermos um gerador de sincronização ponto return realm web fechará a conexão HTTP isso é para todos que estão assistindo e tentando usar isso em produção, certifique-se de fechar a conexão agora se eu Go aqui de novo e talvez Go ao leitura e então talvez Go uh você vê que ele está fechado nós não vemos que a solicitação de quocient ainda está em execução ele está fechado ótima dica útil sim uh sim você deve estar ciente de que, se quiser usá-lo, vamos pular o preenchimento automático Atlas Search, mas você pode Go para a documentação do MongoDB atmos Atlas Search procurar preenchimento automático e ver como implementar que eu realmente queira manter isso em menos de uma hora uh, então vamos usar gado Atlas Search e é importante ver isso gi f também perfeita e terminamos ótimo, isso é legal, como o fato de que você pode facilmente criar um aplicativo em tempo real de gratuidade, o que é sempre útil é uh, é demais e você sabe que você despertou meu interesse em Angular a fúria é demais e é ainda mais demais agora que mais pessoas a estão usando, um de novo, se você for um pouco mal por não mostrar o Atlas Search do Atlas Search, mas é superfácil de usar e temos alguns atlas online que você pode Go e um check-outVou enviar os links para eles no chat e então sim, se você quiser aprender sobre a Pesquisa de Texto Completo com certeza Go em frente e verifique-os sim e então há um bom sim meu atlasearchworkshop.com favorito para que você mesmo faça o curso sim sim isso é bom sim isso foi demais acha que enviei o link errado você envia o link correto e isso é obrigado qual é o preço do aplicativo é totalmente gratuito Instalei no Firebase um Hospedagem no Firebase qual h como camada grátis muito gratuita uh o backend é grátis temos um milhão três solicitações por mês o banco de dados é gratuito temos um cluster gratuito que você pode distribuir nem precisa fornecer seus cartões de crédito ao se registrar no Atlas e comece a usá-lo uh e sim, espero ter respondido a essa pergunta manutenção e atualizações que você pode distribuir quantas quiser, quer dizer, há uma certa limitação de certificados que você pode fazer em uh Hospedagem no Firebase, mas é um número bem alto Eu implantei o aplicativo 10 vezes hoje e significa que sim, e isso não está vinculado ao Firebase, é no sentido de que você pode escolher outra plataforma de hospedagem e tudo ficará bem sim, sim, você pode usar qualquer outra plataforma de hospedagem, posso tente implementá-lo na interface do usuário com o Azure e veja como funciona Estou certo de que vai funcionar é um aplicativo web simples uh não há nada de realmente especial nele e qualquer pessoa que seja durão o suficiente para escrever seu código no Vim no meio de uma transmissão ao vivo Eu cruzo o código deles, sim uh s omeone está perguntado qual é o melhor, mais eficiente em termos de custos para startups Firebase ou MongoDB, então não há uma resposta definitiva em primeiro lugar uh Firebase está usando firestore sob o capô MongoDB Atlas está usando MongoDB ambos são bancos de dados de documentos em minha opiniao MongoDB é mais sofisticado mais capaz como banco de dados O Firebase como serviço tem alguns recursos adicionais que são incríveis, mas depende do que você precisa em seu aplicativo e, se você for uma startup, ambas as empresas Google Cloud Platform e MongoDB têm ótimos programas de inicialização que nós na verdade, tem um programa de inicialização conjunto com Google Cloud Platform para que você possa se inscrever no programa conjunto e obter créditos grátis pelos créditos grátis do Atlas para Google Cloud Platform e participar de suporte como sessões técnicas, sessões de serviço ao cliente também uh, definitivamente, você pode usar sim e temos sim e obviamente você está falando sobre o Firebase nessa pergunta, mas será que temos as mesmas Parcerias de inicialização com a Microsoft e d um e a Amazon também, portanto, se você sabe se quer fazer isso com a Amazon Web Services ou o Azure , não estou ciente dos detalhes em termos de permissão por si só e dos critérios de referência, mas com certeza você sabe que pode escolher qualquer uma que funcione uh alguém enviará esta pergunta algumas vezes outra pessoa também fez podemos gravar isso estará disponível instantaneamente no Youtube uh já que assim que isso terminar e eu tiver certeza de que estou no LinkedIn ele aparece apenas em nosso feed no perfil do MongoDB, então sim, a gravação está disponível apenas lá e, em seguida, queremos compartilhar conhecimento, obviamente, isso foi feito como parte da MongoDB Tv, então recomendamos fortemente que as pessoas uh Go para MongoDB.tv uh você pode assistir em qualquer plataforma que você prefere, mas o Youtube é melhor porque você pode curta e se inscrever no canal, o que é sempre bom sim, uh, então se tiver alguma dúvida, terminaremos a transmissão ao vivo em breve, mas sim, só preciso ter certeza de que não alguém tem alguma pergunta antes e terminamos se as pessoas tiverem alguma pergunta de acompanhamento espelhar após a transmissão ou se estiverem assistindo isso como um uh gravado onde as pessoas podem entrar em contato com você se tiverem alguma pergunta, obviamente, sempre recomendamos os fóruns do uh como o primeiro ponto de chamada para qualquer pergunta, mas caso seja algo que só você poderia responder um sim, tenho certeza de que não há resposta, apenas eu posso responder Lamento uh sim, estou no Twitter LinkedIn Facebook LinkedIn embora caricatura no Twitter tenha certeza de que eu faço o mesmo no LinkedIn , você teria visto meu nome aparecer algumas vezes no chat porque estava respondendo a algumas perguntas da minha página do LinkedIn , mas sim, nós sempre recomendamos que as pessoas Go para Fóruns porque nós muitos há muitas pessoas inteligentes lá que podem responder às suas perguntas e, é claro,somos grandes f questionar outro pe Ruby pode se beneficiar de uma maneira bonita, bonita, bonita, então é isso que eu preciso para aprender a grana neste mês. on Rails uh Eu realmente não reconheço Ruby ou ferrovias, mas aprenderam à medida que avançava e, por isso, vamos seguir o tutorial que criei uh para isso e então começaremos a implementar de forma realmente saudável no Atlas Search se pudermos ser legais, sim, verei todos, acha que é meu Prazer, obrigado por ter aqui ido, é sempre bom sair e você sempre apenas demonstra coisas legais, então eu sempre aprendo muito com você. próximo programa obrigado sim e sim ele disse MongoDB ponto de Tv onde temos uma programação para que você possa ver todos os próximos podcasts e streams ao vivo que temos e vídeos porque é sempre tempo de uh aprender o tempo todo, certo I vê-los a todos no 30 31o fim de semana de agosto a todos tchau

Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Vídeo
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Construindo com padrões: o padrão bucket


May 16, 2022 | 3 min read
Início rápido

Primeiros passos no MongoDB e Starlette


Jul 12, 2024 | 5 min read
Tutorial

Como se conectar ao MongoDB com um proxy SOCKS5 com Java


Aug 29, 2024 | 2 min read
Artigo

Usando Change Streams do MongoDB em Java


Aug 28, 2024 | 6 min read