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);
});
}
但在響應,customer
是null
。
測試數據我用:
用戶文檔:
{
"_id" : ObjectId("570d1f0938f7da5151b815d2"),
"customer" : ObjectId("570d1f0838f7da5151b815d0"),
...
}
的相關客戶資料:
{
"_id" : ObjectId("570d1f0838f7da5151b815d0"),
...
}
可能是一個noob問題,但我不明白我沒有看到我能忘記什麼=)
對我來說很好。你是否等待(完成回調)在填充查詢之前將文檔保存起來? – lipp
是的:/ (這裏只是沒用的文字,因爲SO接受最少15個字符的評論xD) –