3

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);
  });
}
1
  • 1
    Use the framework mongoose. Found here mongoosejs.com Commented Dec 4, 2012 at 10:53

2 Answers 2

3

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');
});
Sign up to request clarification or add additional context in comments.

Comments

3

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:[email protected]/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) { ... });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.