且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将MongoDB连接到前端?

更新时间:2022-05-28 09:10:57

简答:你没有。

长答案: MongoDB不是为了直接向客户端公开数据而设计的。客户端与Web服务器上的应用程序交互 - 在您的情况下在Node.js中实现 - 并且Web服务器与数据库进行通信。

Long answer: MongoDB isn't designed to expose data directly to the client. The client interacts with the application on the webserver - in your case implemented in Node.js - and the webserver communicates with the database.

+---------+    +---------+    +---------+ 
|Browser  |    | Node.js |    | MongoDB | 
|        ------->        |    |         |    
|         |    |         |    |         |
|         |    |        ------->        |
|         |    |         |    |         |
|         |    |         |    |         |
|         |    |        <-------        |    
|         |    |         |    |         |   
|        <-------        |    |         | 
|         |    |         |    |         |  
+---------+    +---------+    +---------+  

这意味着在实践中,在用户浏览器中执行的javascript客户端应用程序向Node.js发送请求(通过普通页面请求,通过Websockets通过XmlHttpRequest或其他一些方法)。 Node.js接受此请求,然后联系MongoDB以获取实现它所需的数据。当Node.js从数据库接收数据时,它使用它来构建响应,并将其发送到客户端。

This means in practice, that the javascript client application executed in the users browser sends a request to Node.js (via a normal page request, via XmlHttpRequest via Websockets or some other method). Node.js accepts this request and then contacts MongoDB for the data required to fulfill it. When Node.js received the data from the database, it uses it to build the response, and sends it to the client.

客户端应用程序没有意识到服务器使用后端数据库来完成请求。

The client application doesn't realize that the server used a backend database to fulfill the request.

我的学习建议是暂时退出数据库。使用angular.js使客户端从Node.js服务器应用程序加载一些静态数据。当你使用它时,扩展服务器端以从MongoDB获取数据。

My learning recommendation for you is to leave the database out for now. Use angular.js to make the client load some static data from the Node.js server application. When you got this working, extend the server-side to obtain the data from MongoDB.