Mongo query a JSON.stringify key


#1

This is sort of a weird question to phrase. I have a key-value which is a JSON.stringify’d array. At the console, this is what happens:

Events.findOne()["[1434774822211,34.0320946,-118.28024160000001]"]
// => true
Events.findOne({"[1434774822211,34.0320946,-118.28024160000001]":true})
// => undefined

I cant query on that key for some reason. I don’t understand why.

Now, you may be wondering why I’m doing such a crazy thing. Well the three values in that array are a timestamp, latitude and longitude. I have a publish function that takes in these values:

Meteor.publish 'events', (limit, time, lat, lng) ->
  r = 0.25
  
  cursor = Events.find({
    start: { $gt: time },
    lng: { $gt: lng-r, $lt: lng+r },
    lat: { $gt: lat-r, $lt: lat+r }
  }, {
    limit: limit, 
    sort: { start: 1, title: 1 }
  })

  publishCursorWithKey(JSON.stringify([time, lat, lng]), cursor, this)
  return

publishCursorWithKey = (key, cursor, pub) ->
  name = cursor._cursorDescription.collectionName
  observe = cursor.observeChanges 
    added: (id, fields) =>
      fields[key] = true
      pub.added(name, id, fields)
    changed: (id, fields) =>
      @pub.changed(name, id, fields)
    removed: (id) =>
      @pub.removed(name, id)
  pub.ready()
  pub.onStop ->
    observe.stop()

I use JSON.stringify on the arguments and set that as a key to each document that is published so that I can distinguish what results belong to which subscription.

Ideally, I’d like to be able to do this:

Meteor.subscribe('events', limit, time, lat, lng, function() {
  selector = {}
  selector[JSON.stringify([time, lat, lng]) = true
  console.log(Events.find(selector).fetch())
})

But that selector doesnt seem to work for some reason… any ideas?


More investigation:

Posts = new Mongo.Collection(null)
Posts.insert({"1234": true})
//=> "Aw2JvsbjEz7nM5PuY"
Posts.find({"1234":true})
Posts.find({"1234":true}).count()
//=> 1
Posts.insert({"[1234]": true})
//=> "SyExzvfH29p864g4R"
Posts.find({"[1234]":true}).count()
//=> 1
Posts.insert({"[1234, 123, -23.2]": true})
//=> "NsDw2RNbLbLQHePaW"
Posts.find({"[1234, 123, -23.2]":true}).count()
//=> 0
Posts.insert({",": true})
//=> "iAX8Rgm6ahMCQRatm"
Posts.find({",":true}).count()
//=> 1
Posts.insert({"-": true})
//=> "66AEqRfGNxvSdPS8R"
Posts.find({"-":true}).count()
//=> 1
Posts.insert({" ": true})
//=> "GEmgr38mH47FQPGs9"
Posts.find({" ":true}).count()
//=> 1
Posts.insert({"[1234,1234]": true})
//=> "YzpRJ3nQoNcBvyYTs"
Posts.find({"[1234,1234]":true}).count()
//=> 1
Posts.insert({"[1234,-1234]": true})
//=> "RBjP3kKXaNsJjBLwg"
Posts.find({"[1234,-1234]":true}).count()
//=> 1
Posts.insert({"[1234, -1234]": true})
//=> "eRRzysGuxbCqQoMts"
Posts.find({"[1234, -1234]":true}).count()
//=> 1

ah HA – the f’ing dot!!