从MongoDB + Node.js获取数据到客户端JavaScript

时间:2012-12-04 10:52:45

标签: node.js mongodb

如何使用Node.js连接MongoDB?然后将结果传递给客户端JavaScript并以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);
  });
}

2 个答案:

答案 0 :(得分:3)

你应该使用Mongoose - 为node.js设计优雅的mongodb对象。 http://mongoosejs.com

快速入门指南真的很酷,你应该read it

根据文档,这是一个如何使用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');
});

答案 1 :(得分:3)

我更喜欢MongoJS到Mongoose,因为它使用与MongoDB客户端语法相同的语法 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');

然后您可以使用与Mongo客户端相同的语法

db.mycollection.find({}, function(err, docs) { ... });

db.mycollection.find({}).limit(2).skip(1, function(err, docs) { ... });