Tech Blog :: Quick tip: Share a large MongoDB query object between the CLI and Node.js


May 24 '12 1:10pm

Quick tip: Share a large MongoDB query object between the CLI and Node.js

I was writing a very long MongoDB query in JSON that needed to work both in a Mongo CLI script and in a Node.js app. Duplicating the JSON for the query across both raised the risk of one changing without the other. So I dug around for a way to share them and came up with this:

Create a query.js file, like so (the query is just an example, substitute your own):

// dual-purpose, include me in mongo cli or node.js
var module = module || {};    // filler for mongo CLI
 
// query here is for mongo cli. module.exports is for node.js
var query = module.exports = {
  '$and' : [
    { '$or' : [ 
      { someField: { '$exists': false } }, 
      { someOtherField: 0 } 
    ] },
 
    { '$or' : [ 
      { 'endDate' : { '$lt' : new Date() } },
      { 'endDate' : { '$exists' : false } }
    ] }
 
    // ...  
  ]
};

Then in your mongo CLI script, use

load('./query.js');   // sets query var
 
db.items.find(
    query,
 
    {
      // fields to select ...
    }
  )
  .sort({
    // etc...
  });

In your Node.js app, use var query = require('./query.js'); and plug the same query into your MongoDB driver or Mongoose find function. Duplication avoided!