Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for structuring Express routes that handle MongoDB queries

I am building a RESTful service for querying a movie database using Express.js, Node.js and MongoDB and I am a beginner on all of them.

My question is what is the best practice for structuring db queries with Node so that I take advantage of the callback mechanisms and not block the server but at the same time not write bloated code.

I modified the code provided by the express-generator and I think it achieves the former but not the latter. What are your comments?

If you could provide a general skeleton for an Express route that handles db queries, I would appreciate it.

Below is my code

var findMovie = function(db, callback, req, res) {
var path = req.path.split("\/");
var cursor = db.collection('movies').find({"_id" : ObjectId(path[path.length - 2])});

var query = [];
cursor.each(function(err, doc) {
    assert.equal(err, null);
    if (doc != null) {
        query.push(doc);
    } else {
        res.json(query);
        callback();
    }
});

}

router.get('/movies/:id/info/', function(req, res, next){
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  findMovie(db, function() {
      db.close();
  }, req, res);
});

});

like image 540
adkalkan Avatar asked Dec 02 '25 06:12

adkalkan


1 Answers

First if you use mongoDB in node i will definately recommend to use mongoose or some other object modeling tool, its much easier than native driver.

then it might look like this:

/model/user.js

var mongoose =  require('mongoose');

var UserSchema = new mongoose.Schema({
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
    email: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    active: {type: Boolean, default: true},
    role: {type: String, default: 'user'},
    accessLevel: {type: Number, default: 1}
  }, {
    collection: 'users'  
});

module.exports = mongoose.model('User', UserSchema);

/controllers/users.js

var User = require('../model/user');

exports.create (req, res, next) {
  var newUser = new User(req.body);

  newUser.save(function (err) {
      if (err)
        return next(err);
      res.json({
        message: 'User created'
      });
  });
}

exports.listAll (req, res, next) {
  User.find({}, function (err, users) {
      if (err)
        return next(err);
      res.json(users)
  });
}

exports.getById (req, res, next) {
  User.findById(req.params.id, function (err, user) {
      if (err)
        return next(err);
      res.json(user)
  });
}

/routes/users.js

var controller = require('../controllers/users');
var router = require('express').Router();

router.route('/users')
  .post(controller.create)
  .get(controller.listAll)

router.route('/users/:id')
  .get(controller.getById)
  .delete(controller.remove)
like image 146
Jakub Martyčák Avatar answered Dec 03 '25 20:12

Jakub Martyčák



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!