【发布时间】:2016-07-06 11:38:35
【问题描述】:
我在 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')
}
]
可能是什么问题?以及如何解决?
附:我已将 payment: { type: Number, ref: 'Payment' } type 更改为 ObjectId,但问题未解决
【问题讨论】:
-
从您的 PaymentSchema 中删除 _id。
-
都一样。返回 null 而不是 ObjectId
-
在您的 CardSchema 中,Payment 是 Number 类型。但是,您的 Mongotron 输出显示支付 ObjectId。想知道为什么?
-
我希望我知道。但是,如果更改为 ObjectId - 您的方法同样不起作用。 Mongotron 返回 ObjectId、console.log - 支付字段返回 NULL
-
您是否从数据库中检查过(比如使用 mongo shell)这些 ID 是否确实存在于 MedicalCards 集合的医疗卡文档中?
标签: node.js mongodb mongoose mongoose-populate