I've defined simple connection to mongo db to fetch all saved records into database and show I get null and my findAll
does not work:
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;
for get all saved data in article
database, i'm testing log and find all saved records into article
from mongo shell:
> db.article.find()
{ "_id" : ObjectId("55033f527be6c3a7bc7e5b04"), "title" : "Post two", "body" : "Body two" }
{ "_id" : ObjectId("55033f527be6c3a7bc7e5b05"), "title" : "Post three", "body" : "Body three" }
>
in my nodejs Route i get null and i can not get this records from my application
My nodejs server:
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);
});
My Route content file:
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();
});
};
You #getCollection method on the ArticleProvider prototype property has a syntax error, for starters. You could get rid of #getCollection all together, not sure what you are doing with it. I think you are trying to just query the db for all the article documents in that collection? Try this:
ArticleProvider.prototype.findAll = function(callback) {
this.db.collection('article').find({}, function(error, results) {
if (error) {
callback(error);
} else {
callback(null, results);
}
});
};