Can Javascript natively connect to MongoDB?

徘徊边缘 提交于 2020-01-30 11:24:48

问题


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.

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.

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.

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
});

回答1:


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.



来源:https://stackoverflow.com/questions/24330905/can-javascript-natively-connect-to-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!