方法适用于开发但不适用于生产Rails MongoDB

我有优惠券课程,我希望我的应用程序检查并查看优惠券上剩余的计数以及优惠券的日期是否已过期。 我class上有以下方法来检查这两个方法。

Coupon class def self.get(code) where( :code => (normalize_code(code)), :$and => [ { :$or => [ { :coupon_count.gte => 1 }, { :coupon_count => nil } ] }, { :$or => [ { :expires_at.gt => Time.now.utc }, { :expires_at => nil } ] } ] ).first end 

当我输入优惠券时,这在开发中工作正常。 但在生产中它不起作用。 我使用我的MongoDB shell创建优惠券,如下所示。

 db.Coupon.insert({code:'#COUPONNAME',discount_percent: 10, expires_at: new ISODate("2016-05-18"), coupon_count: 10, "description": '1st cold visit sign-up'}) 

好像是优惠券检查expires_at日期时的问题。 在开发中它找到优惠券并且有效,但在生产中它一直没有找到优惠券。 这里有一个很好的衡量标准是我的控制器方法。

编辑我认为问题是与日期,但如果我删除日期查询它仍然无法生产。 我很困惑,为什么这在生产中不起作用。 它使用的是MongoDB 3.0.10和mongoid 5.1.0 gem


 charges_controller @code = params[:couponCode] if !@code.blank? @coupon = Coupon.get(@code) if @coupon.nil? flash[:error] = 'Coupon code is not valid or expired.' redirect_to new_managers_charge_path(id: @reportapproval.id) return elsif @coupon.discount_percent == 100 @reportapproval.report_paid = true @reportapproval.free_coupon_used = true @reportapproval.save! @coupon.coupon_count = @coupon.coupon_count - 1 @coupon.save! redirect_to managers_dashboard_path, :notice => "You have successfully requested a pre-paid report from #{@reportapproval.tenant_last_name} with a 'No-Pay' intro coupon." return else @final_amount = @coupon.apply_discount(@amount.to_i) @discount_amount = (@amount.to_i - @final_amount.to_i) end 

如果您有Coupon Mongoid模型,那么MongoDB shell中的集合将是db.coupons 。 这可以解释原因:

 db.Coupon.insert(...) 

在MongoDB shell中没有提供您期望在Rails代码中找到的内容。


至于Neil关于$exists与明确的nil检查的评论,我认为你确实想要nil (MongoDB中的AKA null )检查。 在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") } 

所以我们有一个集合,其中包含n ,没有nn显式null值和nnull值的文档。

然后我们可以看到Mongoid查询之间的区别,如:n => nil

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

:n.exists => true (又名:n => { :$exists => true } ):

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

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

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

因此:expires_at => nil查询将查找没有expires_at文档以及expires_at显式设置为nil文档。 这两种情况都会发生在Mongoid上,除非你小心地调用remove_attribute而不是指定一个nil ,两种情况都意味着“没有过期日期”。