2014-02-06 66 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)