Reputation: 105
I'm making a hire platform for cars. Now i used mongoose, setup my models and found out i can't populate a reference that's too deep.
I got 2 models: Cars and Types and Customers. I'm trying to receive everything from my Customers like placed orders. The response i'm getting currently is the one below.
"slug": "myslug",
"note": "",
"isReturned": false,
"includedKM": "0",
"price": "0",
"car": {
"type": "_id"
}
I got the car to populate but i can't seem to get the type to populate. I tried things like .populate('car.type')
but with no result. I looked this up and apparently it's too deep to populate so i came up with a solution to bypass this.
const customer = req.customer;
Order.find({'customer': customer.slug}).populate('car').then(function(orders){
Car.find(orders).populate('type').then(function(types){
return res.json(types);
});
});
The types i'm getting now are the populated types from the cars.
Now i want to swap the content of the car.type
to this result and generate my own populated response.
Anyone any clue how to do this? It's probably pretty easy since i have the type_id
in both. Just need to map the data from one to the other.
Thanks in advance!
Upvotes: 0
Views: 2390
Reputation: 855
Send value of car type as parameter or get it inside request in a variable value.
After that you can do it like this:
Order.findOneAndUpdate({customer: customer.slug}, {$set: {car.type: value}}, function (err, customer) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Success',
obj: customer
});
});
Upvotes: 0
Reputation: 11585
Since mongoose 4 you can populate documents across multiple levels.
Maybe this post will help you. mongoose - populate sub-schema sub-array
Upvotes: 1
Reputation: 105
Found a solution to this problem. Apparently there is a plugin for mongoose (deep-populate) that allows you to populate 2nd grade child references
Upvotes: 0