Best practice for structuring Express routes that handle MongoDB queries

I am creating a RESTful service to query a movie database using Express.js, Node.js and MongoDB and I am new to all of them.

My question is, is it best to structure db requests with Node so that I use callback mechanisms rather than blocking the server, but at the same time not writing bloated code.

I changed the code provided by express generator and I think it reaches the first but not the last. Your comments?

If you could provide a generic skeleton for an express route that handles db requests, I'd 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);
});

      

});

+3


source to share


1 answer


First, if you are using mongoDB in node, I definitely recommend using mongoose or some other object modeling tool, it is much simpler 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)

      

+3


source







All Articles