【问题标题】:Can't find full Model in Mongoose在 Mongoose 中找不到完整模型
【发布时间】: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


【解决方案1】:
var PaymentSchema = new Schema({
  cost: Number,
});
mongoose.model("Payment", PaymentSchema);

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

【讨论】:

  • 唯一需要尝试的是使用上述模型定义,添加一个新的 MedicalCard 文档,向该文档添加新的付款并保存。然后看看填充是否有效。
  • 已检查。不工作。添加新的 PaymentSchema2 和 CardSheme2 并输入字段 payment 并键入 Schema.ObjectId。添加一些元素并使用 .find().population('payment') 后 - 返回结果都一样(没有支付字段的所有正确 - 他的 null,但 mongotron 返回正确的信息)
【解决方案2】:

问题解决下一个解决方案:

1) 在模型支付中 - 删除类型为 Schema.Types.ObjectId 的 _id。

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”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多