title: How do you match by date in mongodb using node js?
body: <p>I have a dataset in a mongo database with elements like this:</p>
  
  <pre><code>{
      "fullname" : "Anonymous User",
      "date" : ISODate("2016-12-09T04:00:27Z")
  }
  </code></pre>
  
  <p>I am trying to search on the date <em>and</em> fullname terms.</p>
  
  <p>In mongo (on the command line) if I do the following command I get a number of elements returned:</p>
  
  <blockquote>
    <p>db.collection_name.find({ $and: [ { fullname: { $regex: "^Anonymous
    User$", $options: 'i' } }, {"date" : {"$lt" :
    ISODate("2016-12-19T00:00:00Z")}} ] }).pretty()</p>
  </blockquote>
  
  <p>when the fullname matches and the date is less than the date given.  This is great so I know my database has the data stored but the date and name are hard-coded.</p>
  
  <p>I am writing a script in node.js and came up with this:</p>
  
  <pre><code>var fullname = "Anonymous User";
  var today = new Date();
  var search_term = { $and: [ { fullname: { $regex: "^" + fullname + "$", $options: 'i' } }, { date: { $lt: today } } ] };
  </code></pre>
  
  <p>I am trying to use the <a href="https://www.npmjs.com/package/mongodb" rel="nofollow noreferrer" title="mongodb">mongodb</a> module and this snippet of code in my nodejs script:</p>
  
  <blockquote>
    <p>db.collection( collection_name ).find( search_term ).toArray( function
    ( err, results ) { console.log(results); } );</p>
  </blockquote>
  
  <p>But when I run my script no results are returned.  There are no error messages - just that no items match and there are no results.</p>
  
  <p>What am I doing wrong?</p>
  
  <p>I think it may be something to do with how the date gets stored in the variable "search_term" but I don't know how to fix this.  For example this works:</p>
  
  <blockquote>
    <p>db.collection( collection_name ).find( { $and: [ { fullname: { $regex:
    "^Anonymous User$", $options: 'i' } }, { date: { $lt: new Date() } } ]
    } );</p>
  </blockquote>
  
  <p>This doesn't work:</p>
  
  <blockquote>
    <p>db.collection( collection_name ).find( search_term ).toArray( function
    ( err, results ) { console.log(results); } );</p>
  </blockquote>
  
  <p>The only difference being I have replaced the find statement with "search_term".</p>
  
  <p>I want to use the latter to avoid code duplication.</p>