Method works in development but not production Rails MongoDB

后端 未结 1 2005
借酒劲吻你
借酒劲吻你 2021-01-26 15:03

I have a Coupon class and I want my app to check and see how many counts are left on the coupon and if the date for the coupon has expired. I have the following method in my cla

相关标签:
1条回答
  • 2021-01-26 15:52

    If you have a Coupon Mongoid model then the collection in the MongoDB shell would be db.coupons. That would explain why:

    db.Coupon.insert(...)
    

    in the MongoDB shell isn't providing what you're expecting to find in your Rails code.


    As far as Neil's comment about $exists versus explicit nil checks goes, I think you really do want nil (AKA null inside MongoDB) checks. Consider this in the MongoDB shell:

    > db.models.insert({ n: 11 })
    > db.models.insert({ n: 0 })
    > db.models.insert({ n: null })
    > db.models.insert({ })
    > db.models.find()
    { "_id" : ObjectId("571546e1ce2934dadf379479"), "n" : 11 }
    { "_id" : ObjectId("571546e4ce2934dadf37947a"), "n" : 0 }
    { "_id" : ObjectId("571546e7ce2934dadf37947b"), "n" : null }
    { "_id" : ObjectId("571546ecce2934dadf37947c") }
    

    So we have a collection with documents that have n, don't have n, have explicit null values for n, and non-null values for n.

    Then we can see the difference between Mongoid queries like :n => nil:

    > db.models.find({ n: null })
    { "_id" : ObjectId("571546e7ce2934dadf37947b"), "n" : null }
    { "_id" : ObjectId("571546ecce2934dadf37947c") }
    

    and :n.exists => true (AKA :n => { :$exists => true }):

    > db.models.find({ n: { $exists: true } })
    { "_id" : ObjectId("571546e1ce2934dadf379479"), "n" : 11 }
    { "_id" : ObjectId("571546e4ce2934dadf37947a"), "n" : 0 }
    { "_id" : ObjectId("571546e7ce2934dadf37947b"), "n" : null }
    

    and :n => { :$exists => false }:

    > db.models.find({ n: { $exists: false } })
    { "_id" : ObjectId("571546ecce2934dadf37947c") }
    

    So the :expires_at => nil queries will find documents which don't have an expires_at as well as documents where expires_at was explicitly set to nil. Both those cases will happen with Mongoid unless you're careful to call remove_attribute instead of assigning a nil and both cases mean "no expiry date".

    0 讨论(0)
提交回复
热议问题