问题
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