How to connect to MongoDB with Node.js? And then pass the result to a client side JavaScript and display in HTML.
var http = require('http');
var URL = require('url');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('people', new Server("127.0.0.1", 27017, {}), { safe: false });
client.open(function (err, client) {
client.collection('people', listAllData);
});
var listAllData = function (err, collection) {
collection.find().toArray(function (err, results) {
console.log(results);
});
}
You should use Mongoose - elegant mongodb object modeling for node.js. http://mongoosejs.com
The quickstart guide is really cool, you should read it.
According to the documentation, here is a small example of how to use Mongoose:
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');
var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
I prefer MongoJS to Mongoose because it uses the same syntax used by the MongoDB Client syntax https://github.com/gett/mongojs
// simple usage for a local db
var db = mongojs('mydb', ['mycollection']);
// the db is on a remote server (the port default to mongo)
var db = mongojs('example.com/mydb', ['mycollection']);
// we can also provide some credentials
var db = mongojs('username:password@example.com/mydb', ['mycollection']);
// connect now, and worry about collections later
var db = mongojs('mydb');
var mycollection = db.collection('mycollection');
Then you can use the same syntax as the Mongo Client
db.mycollection.find({}, function(err, docs) { ... });
db.mycollection.find({}).limit(2).skip(1, function(err, docs) { ... });