I have twoo collections I would like to preform a 'join' on.
The first one who has the reference is parrent.
The second one is calld child
This is how the object parrent looks like:
{
"_id": "id_123"
"name": "name",
"children": ["id_child_1", "id_child_2", ...]
}
model/par.js looks like this:
const mongoose = require('mongoose');
const Par= mongoose.model('parrent',new mongoose.Schema({}), 'parrent');
exports.Par= Par;
route/par.js looks like this:
const {Par} = require('../models/par');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) => {
const par = await Par.find();
res.send(par);
});
module.exports = router
The route child and model child looks exactly the same. (This is a simplefied version of the case).
I would like to return something like this:
{
"_id": "id_123"
"name": "name",
"children": [{"name":"child1"}, {"name":"child2"}, ...]
}
I couldn't find a solution that worked, is not depricated, or one that uses this architecture.
CodePudding user response:
If I've understood correctly you can get it using simply a $lookup
like this:
db.parent.aggregate([
{
"$lookup": {
"from": "child",
"localField": "children",
"foreignField": "_id",
"as": "children"
}
}
])
Example here
Or using $project
to not output the _id
in children array: example