Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MongoDB from client with Javascript

I am trying to use MongoDB with just javascript from client, but MongoDB's documentation on how to achieve this is very confusing.

On this webpage there is nothing to download, I was expecting to see something like mongo.js.

Here I did find mongo.js, and using this I am trying to make it work but with no luck.

The Javascript console in Google Chrome is saying:

Uncaught TypeError: Object [object Object] has no method 'init'

In this snippet from mongo.js:

if ( typeof Mongo == "undefined" ){   Mongo = function( host ){     this.init( host );     } } 

Does anyone have any tips on using MongoDB with pure Javascript?

like image 358
deloki Avatar asked Apr 29 '13 10:04

deloki


People also ask

Can we connect MongoDB with JavaScript?

MongoDB is a document-based NoSQL database that stores data in BSON (JSON-like) format. JavaScript is unanimously the most popular language for building web applications. It can also be used for building server-side applications usingNode. js.

Can MongoDB be used from frontend?

Short answer: You don't. 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.

How do you retrieve data in MongoDB using JavaScript?

To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.


1 Answers

The documentation you linked to is about accessing MongoDB with server-sided Javascript using the node.js framework.

MongoDB does offer a REST webservice allowing rudimentary queries through XmlHttpRequests. To enable it, you have to start mongod with the --rest parameter. You can then query it like this:

http://127.0.0.1:28017/yourDatabase/yourCollection/?filter_name=Bob 

You can query this URL with an AJAX XmlHttpRequest like any webservice. It will access a database on localhost and return JSON equivalent to a query like this:

yourDatabase.yourCollection.find({name:"Bob"}); 

This interface, however, is very rudimentary. It only offers simple find queries. But there are 3rd party middleware layers which expose more advanced functionality. This feature and a list of 3rd party solutions is documented here:

http://docs.mongodb.org/ecosystem/tools/http-interfaces/

like image 53
Philipp Avatar answered Sep 26 '22 01:09

Philipp