无法在Mongoose中找到完整的模型

时间:2016-03-19 19:15:05

标签: node.js mongodb mongoose mongoose-populate

我在Mongoose populate中找到完整模型时遇到问题。

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。我已经更改了付款:{type:Number,ref:'付款' }类型到ObjectId,但问题未解决

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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”