2016-03-19 113 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”