nodejs从mongodb数据库获取所有集合

时间:2015-03-13 20:18:04

标签: node.js mongodb

我已经定义了与mongo db的简单连接,以便将所有已保存的记录提取到数据库中,并显示我得到null并且我的findAll不起作用:

var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;

ArticleProvider = function (host, port) {
    this.db = new Db('article', new Server(host, port, {auto_reconnect: true}), {safe:false});
    this.db.open(function () {
    });
};

ArticleProvider.prototype.getCollection = function (callback) {
    this.db.collection('article'), function (error, article_collection) {
        if (error) callback(error);
        else callback(null, article_collection);
    }
};

ArticleProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            article_collection.find().toArray(function(error, results) {
                if( error ) callback(error)
                else callback(null, results)
            });
        }
    });
};

exports.ArticleProvider = ArticleProvider;

用于获取article数据库中的所有已保存数据,我正在测试日志并从mongo shell中查找所有已保存的记录到article

> db.article.find()
{ "_id" : ObjectId("55033f527be6c3a7bc7e5b04"), "title" : "Post two", "body" : "Body two" }
{ "_id" : ObjectId("55033f527be6c3a7bc7e5b05"), "title" : "Post three", "body" : "Body three" }
> 

在我的nodejs中,路由i得到null,我无法从我的应用程序中获取此记录

我的nodejs服务器:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('../')(server);
var connect = require('connect');
app.use(connect.logger('dev'));
app.use(connect.json());  
app.use(connect.urlencoded());


require('../routes/routes.js')(app);

var port = process.env.PORT || 3000;
server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

我的路线内容文件:

var ArticleProvider = require('config/models/connection').ArticleProvider;
var articleProvider = new ArticleProvider('localhost', 27017);

module.exports = function (app) {
    app.get('/', function (req, res) {
        articleProvider.findAll( function(error,docs){
            console.log(docs);
        });
        res.end();
    });

};

1 个答案:

答案 0 :(得分:0)

对于初学者,ArticleProvider prototype属性上的#getCollection方法有语法错误。你可以一起摆脱#getCollection,不知道你在做什么。我想您正在尝试只查询该集合中所有文章文档的数据库?试试这个:

ArticleProvider.prototype.findAll = function(callback) {
  this.db.collection('article').find({}, function(error, results) {
    if (error) {
      callback(error);
    } else {
      callback(null, results);
    }
  });
};