2016-03-19 86 views
0

我在Mongoose populate中找到完整模型時遇到問題。在Mongoose中找不到完整模型

2款貓鼬:

//first 
var CardSchema = new Schema({ 
    userId: String, 
    payment: { type: Number, ref: 'Payment' } 
}); 
module.exports = mongoose.model('MedicalCard', CardSchema); 
//second 
var PaymentSchema = new Schema({ 
    _id: Schema.Types.ObjectId, 
    cost: String, 
}); 
module.exports = mongoose.model('Payment', PaymentSchema); 

而且我希望找到所有推車某些用戶:

CardModel.find({ userId: id}).populate('payment').exec(function (err, data) { 
     if (err) { 
      //error 
     } 

     if (data) { 
      console.log(data); 
     } 
    }); 

但對我來說返回結果:

[ 
    { 
    "_id": "56ed9993a5c9067a21edec69", 
    "userId": "56eaccec930c15cf245a86a1", 
    "payment": null, 
    "__v": 0 
    }, 
    { 
    "_id": "56ed99a7a5c9067a21edec6d", 
    "userId": "56eaccec930c15cf245a86a1", 
    "payment": null, 
    "__v": 0 
    } 
] 

但Mongotron換取我正確結果:

[ 
    { 
    "_id": ObjectId('56ed99a7a5c9067a21edec6d'), 
    "userId": 56eaccec930c15cf245a86a1, 
    "payment": ObjectId('56ed99a7a5c9067a21edec6a') 
    }, 
    { 
    "_id": ObjectId('56ed9993a5c9067a21edec69'), 
    "userId": "56eaccec930c15cf245a86a1", 
    "payment": ObjectId('56ed99a7a5c9067a21edec6c') 
    } 
] 

可能是什麼問題?以及如何解決它?

P.S.我已經改變了付款方式:{類型:數字,REF: '付款'}鍵入的ObjectId,但問題沒有解決

+1

刪除從_id您的PaymentSchema。 –

+0

都一樣。在您的CardSchema中返回null而不是ObjectId – ximet

+0

,支付類型爲Number。但是,您的Mongotron輸出顯示支付ObjectId。想知道爲什麼? –

回答

0
var PaymentSchema = new Schema({ 
    cost: Number, 
}); 
mongoose.model("Payment", PaymentSchema); 

var CardSchema = new Schema({ 
    userId: String, 
    payment: { type: Schema.ObjectId, ref: 'Payment' } 
}); 
+0

檢查。不工作這 – ximet

+0

唯一剩下的嘗試是與上述模型定義,添加一個新的醫療卡文件,添加一個新的付款到該文件和保存,然後查看填充是否正常工作 –

+0

已檢查不工作添加新的PaymentSchema2和CardSheme2與現場支付和類型Schema.ObjectId添加一些元素並使用.find()。population('payment') - 返回結果all同樣的(所有正確的沒有付款領域 - 他null,但mongotron返回正確的信息) – ximet

0

問題解決了一個解決方案:

1)在模型付款 - 刪除與_id類型Schema.Types.ObjectId。

2)在代碼

CardModel.find({ userId: id}).populate('payment').exec(function (err, data) {//some code}); 

刪除.populate:

CardModel.find({ userId: userInfo.userId},function (err, cards) {//some code}); 

而現在對我來說正確的結果,這個方法的返回: 「支付」: 「56eda8d90982166222480a9f」