Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9086311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T21:27:29+00:00 2026-06-16T21:27:29+00:00

I am using node + express to create a simple REST API, and am

  • 0

I am using node + express to create a simple REST API, and am trying to separate out routing logic from db logic. I am having a problem getting access to the DB from the routes.

Here is my server.js code:

var express = require('express')
  , path = require('path')
  , http = require('http')
  , mongo = require('mongodb');

// Configure Express app
var app = express();
app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser()),
    app.use(express.static(path.join(__dirname, 'public')));
});

// Configure DB
var Server = mongo.Server
  , Db = mongo.Db
  , BSON = mongo.BSONPure
  , server = new Server('localhost', 27017, {auto_reconnect: true})
  , db = new Db('mydb', server, {safe: true});

// Open DB to see if we need to populate with data
db.open(function(err, db) {
  if(!err) {
    console.log("Connected to 'mydb' database");
    var Post = require('./routes/posts')
      , post = new Post(db);

    // Set the routes
    app.get('/:org/posts', post.find);
    app.get('/:org/posts/:id', post.get);
    app.post('/:org/posts', post.add);
    app.put('/:org/posts/:id', post.update);
    app.delete('/:org/posts/:id', post.remove);

    // Fire up the server
    http.createServer(app).listen(app.get('port'), function () {
      console.log("Express server listening on port " + app.get('port'));
    });
  }
});

and here is the logic in the post.js file:

var Post = function(db) {
  this.db = db;
};

Post.prototype.get = function(req, res) {
  var id = req.params.id;
  var org = req.params.org;
  var db = this.db;

  console.log('Retrieving post: ' + id + ' from org: ' + org);
  db.collection('ads', function(err, collection) {
    collection.findOne({'_id':new BSON.ObjectID(id), 'org':org}, function(err, item) {
      res.send(item);
    });
  });
};

Post.prototype.find = function(req, res) {
  var org = req.params.org;
  var db = this.db;

  console.log('Finding posts for org: ' + org);
  db.collection('posts', function(err, collection) {
    collection.find({'org':org}).toArray(function(err, items) {
      res.send(items);
    });
  });
};

Post.prototype.add = function(req, res) {
  var org = req.params.org;
  var post = req.body;
  var db = this.db;

  console.log('Adding post: ' + JSON.stringify(post) + ' for org: ' + org);
  db.collection('posts', function(err, collection) {
    collection.insert(post, {safe:true}, function(err, result) {
      if (err) {
        res.send({'error':'An error has occurred'});
      } else {
        console.log('Success: ' + JSON.stringify(result[0]));
        res.send(result[0]);
      }
    });
  });
};

Post.prototype.update = function(req, res) {
  var id = req.params.id;
  var org = req.params.org;
  var post = req.body;
  var db = this.db;

  delete post._id;
  console.log('Updating post: ' + id + ', org: ' + org);
  console.log(JSON.stringify(post));
  db.collection('posts', function(err, collection) {
    collection.update({'_id':new BSON.ObjectID(id)}, post, {safe:true}, function(err, result) {
      if (err) {
        console.log('Error updating post: ' + err);
        res.send({'error':'An error has occurred'});
      } else {
        console.log('' + result + ' document(s) updated');
        res.send(post);
      }
    });
  });
};

Post.prototype.remove = function(req, res) {
  var id = req.params.id;
  var org = req.params.org;
  var db = this.db;

  console.log('Deleting post: ' + id + ', org: ' + org);
  db.collection('posts', function(err, collection) {
    collection.remove({'_id':new BSON.ObjectID(id), 'org':org}, {safe:true}, function(err, result) {
      if (err) {
        res.send({'error':'An error has occurred - ' + err});
      } else {
        console.log('' + result + ' document(s) deleted');
        res.send(req.body);
      }
    });
  });
};

module.exports = Post;

I would think that the post object would hold on to the db reference for use when it is called from the routes, but I get the following error:

TypeError: Cannot call method 'collection' of undefined
    at Post.find (../routes/posts.js:23:6)

Can anyone point me in the right direction? Many thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T21:27:30+00:00Added an answer on June 16, 2026 at 9:27 pm

    Your post object is lost as the this in your Post methods when called by the Express route handlers you’re registering. You need to bind the methods to your post instance so that no matter how they’re called by Express, this will be your post. Like this:

    // Set the routes
    app.get('/:org/posts', post.find.bind(post));
    app.get('/:org/posts/:id', post.get.bind(post));
    app.post('/:org/posts', post.add.bind(post));
    app.put('/:org/posts/:id', post.update.bind(post));
    app.delete('/:org/posts/:id', post.remove.bind(post));
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using mongoose with express and node to create a REST API. Upon
I'm using Node.js + Express + Passport to create a simple authentication(local) and what
I'm using Node.js, Express and Jade and I'm trying to figure out how to
Background: I am using node.js and express to create an API. I have implemented
I'm using Express.js ontop of Node.js to create RESTful API, and using grunt to
I am using Node.js (with Express.js) to pass a JSON data object from the
I'm (almost) successfully using Node.js with Express and Redis to handle sessions. The problem
I am experiencing this problem with Node.js express framework 3.0: https://github.com/visionmedia/express/issues/1187 I've been using
I wrote a simple application using node. It depends on express, mongodb and mongoose
I am pretty new to CoffeeScript. I am trying to create Node.js application using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.