2014-02-06 96 views
0

我有一個貓鼬模式:貓鼬填充字段爲空

mongoose.Schema({ 
    state: { 
     type: { 
      action: 'string' , 
      user: {type: mongoose.Schema.Types.ObjectId, 
      ref: 'User'}, 
      at: 'date' 
     }, 
    default: {} 
    }, 
    log: [{ 
      action: 'string' , 
      user: {type: mongoose.Schema.Types.ObjectId, 
      ref: 'User'}, 
      at: 'date' 
     }] 
}) 

試圖填充它

Model.findById(id).populate('state.user').populate('log.user').exec(cb) 

在查詢結果「用戶」的日誌項字段填充正確和「的狀態。用戶「爲空。可能是什麼問題?

回答

2

對於簡單的嵌入式對象,如state,定義結構不使用type

mongoose.Schema({ 
    state: { 
     action: 'string' , 
     user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, 
     at: 'date' 
    }, 
    log: [{ 
      action: 'string' , 
      user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, 
      at: 'date' 
    }] 
}) 

populate('state.user')能很好地工作這一點。

+0

我只是想要一個默認值,我看起來像一個bug。 – WHITECOLOR

1

在您的模式中,您有state.type.user,但您致電populate指的是state.user。填充調用中的路徑與模式不匹配。

應該Model.findById(id).populate('state.type.user').populate('log.user').exec(cb)