3

如何使用 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);
  });
}
4

2 回答 2

3

您应该使用 Mongoose - node.js 的优雅 mongodb 对象建模。http://mongoosejs.com

快速入门指南真的很酷,您应该阅读它

根据文档,这里有一个如何使用 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');
});
于 2012-12-04T10:57:40.377 回答
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 Client 一样的语法了

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

db.mycollection.find({}).limit(2).skip(1, function(err, docs) { ... });
于 2013-02-22T11:39:04.010 回答