2016-04-13 84 views
0

User模式中,我簡單參考了Customer模式。未提供參考

const UserSchema = new Schema({ 
    customer: { type: Schema.Types.ObjectId, ref: Customer }, // Customer is the compiled CustomerSchema 
    ... 
}); 

const CustomerSchema = new Schema({ 
    name: String, 
    ... 
}); 

在一個Express控制器,我獲取一個用戶,我試圖嵌入客戶在返回的JSON:

export function me(req, res, next) { 
    User 
    .findOne({ _id: req.user._id }, '-salt -hashedPassword') 
    .populate('customer') 
    .exec((err, user) => { 
     if(err) return next(err); 
     if(!user) return res.json(401); 
     res.json(user); 
    }); 
} 

但在響應,customernull

測試數據我用:

用戶文檔:

{ 
    "_id" : ObjectId("570d1f0938f7da5151b815d2"), 
    "customer" : ObjectId("570d1f0838f7da5151b815d0"), 
    ... 
} 

的相關客戶資料:

{ 
    "_id" : ObjectId("570d1f0838f7da5151b815d0"), 
    ... 
} 

可能是一個noob問題,但我不明白我沒有看到我能忘記什麼=)

+0

對我來說很好。你是否等待(完成回調)在填充查詢之前將文檔保存起來? – lipp

+0

是的:/ (這裏只是沒用的文字,因爲SO接受最少15個字符的評論xD) –

回答

2

我認爲ref必須是一個字符串:

customer: { type: Schema.Types.ObjectId, ref: 'Customer' }, 
+0

是的,謝謝,'ref'必須有一個字符串值,當'mongoose.model(modelName:string,schema: mongoose.Schema)調用'將模式編譯成模型。是的,這是一個noob問題:) –