2014-12-31 77 views
0

我正在使用貓鼬。我只想更新特定用戶訂閱的訂閱狀態。用貓鼬在subdoc上更新

我有以下的數據庫結構:

var subscriptionSchema = new mongoose.Schema({     
      subscription_id   :String, 
      start:      String, 
      status:      String, 
      user_id:     String, 
      cancel_at_period_end:  String, 
      current_period_start:  String, 
      current_period_end:   String, 
      ended_at:     String, 
      trial_start:    String, 
      trial_end:     String, 
      canceled_at:    String, 
      quantity:     String, 
      application_fee_percent: String, 
      discount:     String, 
      tax_percent:    String 
     }); 



// define the schema for our user model 
var userSchema = mongoose.Schema({ 
stripe   : { 
    stripe_customer_id: String, 
    default_card:  String   
}, 
subscriptions: [subscriptionSchema], 
cards: [cardSchema] 
}); 

我有這樣的代碼,它不拋出任何錯誤,但它並沒有任何更新的狀態。有任何想法嗎? Subscription_id對記錄是唯一的。用戶可能有多個訂閱

var user = require('./models/user'); 

user.update(
    { 
    'subscriptions.subscription_id':updatedsubscription_id 
    }, 
    { 
     status: updatedsubscription_status 
    }, 
    { upsert: true }, function(err, doc){ 
    if (err) return console.log(err); 
    return console.log('updated the subscription in db'); 
} 
); 

回答

1

當ID更新數組元素,你可以使用$ positional operator在您的更新對象,以表示查詢匹配的元素的索引:

user.update(
    { 
    'subscriptions.subscription_id':updatedsubscription_id 
    }, 
    { 
     'subscriptions.$.status': updatedsubscription_status 
    }, 
    function(err, count){ 
     if (err) return console.log(err); 
     return console.log('updated the subscription in db'); 
    } 
); 
+0

沒錯這就是它!大! – Cookiejest