I have two collections: Clinicas and Medicos . Clinicas can have a lot of Medicos . The relation was made this way:
medico: [{
medicoId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'medicos'
}
}],
And I will have the following json structure:
[
{
"nome": "clinica teste",
"medico": [
{
"_id": "5e011a3796a5f80e3c0c8d20",
"medicoId": {
"_id": "5dc5eef455a8f61698a0f2cd",
"nome": "Hancho Crutis",
}
},
{
"_id": "5e011a3796a5f80e3c0c8d1f",
"medicoId": {
"_id": "5df16e5746783116709f09b7",
"nome": "camilinha",
}
}
],
}
]
What I want is to make a "join" of these data. After a long research, I got this code but the response is always empty. Can someone tell me what am I doing wrong?
Clinicas.aggregate([
{ $unwind: "$medico"},
{ $lookup: {
from: "medicos",
localField: "medicoId._id",
foreignField: "_id",
as: 'nome'
}},
{ $match: {"medicoId._id": "5df16e5746783116709f09b7"}},
])
You need to convert in ObjectId,
var mongoose = require('mongoose');
Clinicas.aggregate([
{ $unwind: "$medico" },
{
$lookup: {
from: "medicos",
localField: "medicoId._id",
foreignField: "_id",
as: 'nome'
}
},
{ $match: { "medicoId._id": mongoose.Types.ObjectId('5df16e5746783116709f09b7') } },
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.