0
votes

I have problem with find full model in Mongoose populate.

2 models mongoose:

//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);

And I want find all carts certain user:

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

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

But for me return result:

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

But Mongotron return for me correct result:

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

what could be the problem? And how fix it?

P.S. I've changed payment: { type: Number, ref: 'Payment' } type to ObjectId, but problem not solved

2
remove _id from your PaymentSchema. - George Chen
all the same. return null instead ObjectId - ximet
in your CardSchema, Payment is of type Number. However your Mongotron output shows payment an ObjectId. Wondering why? - George Chen
I wish I knew. But, If change to ObjectId - your method all the same not worked. Mongotron return ObjectId, console.log - return NULL for payment field - ximet
have you checked from database (say using mongo shell) if those Ids do exist in the medical card documents from MedicalCards collection? - George Chen

2 Answers

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

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

Problem resolved next solution:

1) In model Payment - delete _id with type Schema.Types.ObjectId.

2) In code

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

Delete .populate:

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

And now this method return for me correct result: "payment": "56eda8d90982166222480a9f"