Javascript可以本地连接到MongoDB吗? [英] Can Javascript natively connect to MongoDB?

查看:383
本文介绍了Javascript可以本地连接到MongoDB吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找访问网页(通过<script src=""> </script>)时加载的Javascript脚本/文件(filename.js)是否可以本机连接到MongoDB实例(在同一服务器上运行)并查询一些汇总数据.

I am trying to find if a Javascript script/file (filename.js) that is loaded when accessing a webpage (via <script src=""> </script>) can natively connect to a MongoDB instance (running on the same server) and query for some aggregate data.

然后,我尝试将汇总查询数据(以Mongo中的文档列表形式返回)传递给

I am then trying to pass the aggregate query data (which returns as a list of documents in Mongo) to Morris Charts, so it will display in a bar chart on the webpage.

我唯一能找到的内容是谈论使用Node.js(我不想这样做)或在Mongo shell中加载.js文件.

The only things I have been able to find talk about using Node.js (which I do not want to do), or loading a .js file in the Mongo shell.

有人可以告诉我Javascript文件是否可以与Mongo建立连接吗?如果没有,是否有办法在Python中(运行Flask框架)进行查询并将该数据传递给Javascript文件?

Can someone tell me if a Javascript file can make a connection to Mongo? If not, is there a way to make the query in Python (running the Flask framework) and pass that data to the Javascript file?

我已经测试了以下代码,但未成功(根本没有显示图表):

I have tested the following code, but it was unsuccessful (no charts display at all):

var con = new Mongo();
var db = conn.getDB("DBName");
var query = db.Collection.aggregate(<aggregate query here>);

Morris.Bar({
element: 'bar-chart',
data: query,
xkey: 'x',
ykeys: ['y'],
labels: ['label'],
hideHover: 'auto',
resize: true
});

我还测试了下面的代码,这些代码确实有效:

I also tested the following code, which did work:

var dataset = [
{x: '1', y: 10},
{x: '2', y: 20},
{x: '3', y: 40}
];

Morris.Bar({
element: 'bar-chart',
data: dataset,
xkey: 'x',
ykeys: ['y'],
labels: ['label'],
hideHover: 'auto',
resize: true
});

推荐答案

您不能从客户端浏览器中的javascript文件直接连接到Mongo 如果是这样,请考虑一下安全漏洞. 我认为,针对您的问题的最佳解决方案是将Ajax请求发送至服务器,并以Json的形式获取聚合数据,然后解析该数据并将其输入到图表api.

You cannot make a direct connection to Mongo from a javascript file in client browser Think of the security breach if that was the case. I think the best solution for your problem is to send an Ajax request to the server and get the aggregated data as Json and parse it and give input to the chart api.

这篇关于Javascript可以本地连接到MongoDB吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆