title: Golang/mgo: How can I ask MongoDB to use current time in a field?
body: <p>I have this struct that matches the types of a MongoDB collection I'm using:</p>
  
  <pre><code>type AppInstance struct {
      Id bson.ObjectId "_id,omitempty"
      Url string
      Priority int
      LastSeen string
  }
  </code></pre>
  
  <p>I want the LastSeen field to hold the time of the last interaction with that particular app.  So, the app registers itself setting current time (as a string).</p>
  
  <p>What I would like is Mongo to dynamically set its own current time into that field when it inserts, just like MySQL's NOW() function would do.</p>
  
  <p>I have this helper function: </p>
  
  <pre><code>func mongoNow() bson.JavaScript {
      return bson.JavaScript{Code: 
           "return (new Date()).ISODate('YYYY-MM-DD hh:mm:ss');"}
  }
  </code></pre>
  
  <p>And I tried this:</p>
  
  <pre><code>c := mongoSession.DB("myapp").C("instances")
  rand.Seed(time.Now().UnixNano())
  err := c.Insert(
     struct{Id, Serial, Priority, Url, LastSeen interface{}}{ 
        Id: bson.NewObjectId(), 
        Url: getInformedHost() + ":" + getRunningPortString(), 
        Priority: rand.Int(), 
        LastSeen: mongoNow() }
  )
  checkError(err, "Could not register on MongoDB server.", 3)
  </code></pre>
  
  <p>the LastSeen field gets stored as a script instead of evaluated:</p>
  
  <pre><code>[_id] =&gt; MongoId Object (
      [$id] =&gt; 502d6f984eaead30a134fa10
  )
  [id] =&gt; MongoId Object (
      [$id] =&gt; 502d6f98aa443e0ffd000001
  )
  [priority] =&gt; 1694546828
  [url] =&gt; 127.0.0.1:8080
  [lastseen] =&gt; MongoCode Object (
      [code] =&gt; (new Date()).ISODate('YYYY-MM-DD hh:mm:ss')
      [scope] =&gt; Array (
      )
  )
  </code></pre>
  
  <p>So, I think there are to questions:</p>
  
  <p>First, how can I insert the current time?</p>
  
  <p>Second, how can I get some javascript evaluated instead of inserted?</p>
  
  <p>The answer to the second one could be enough to answer the first one, but it might as well not be.</p>