I am looking for a way to search for data that has a foreign key. But I haven't found it yet. I've been stuck here for a day. Here is my model
const mongoose = require('mongoose');
const UserCGN = mongoose.Schema({
username: String,
cours: String
})
module.exports = mongoose.model('UserCGN', UserCGN);
const mongoose = require('mongoose');
const Cours = mongoose.Schema({
name_Cours: String,
date_Commenc: Date
})
module.exports = mongoose.model('dataCours', Cours);
And I have a data in my database like it
dans UserCGN
username:"njatotianafiononana@gmail.com" cours:"Anglais"
et dans le dataCours
name_Cours:"Anglais" date_Commenc:2022-01-12T00:00:00.000+00:00
Et voici mon code pour récuperer
var coursM = await CoursModel.aggregate( [
{
$lookup:
{
from: "CGNModel",
localField: "name_Cours",
foreignField: "cours",
as: "inventory_docs"
}
}
] )
console.log("coursM", coursM);
In my table inventory_docs is always empty. Please, help me
Are these two models connected in any way? From the snippet you provided, it looks like you forgot to do it, and the model should loke something like this. This way you could do lookup with foreignField: "_id"
const Cours = mongoose.Schema({
name_Cours: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'UserCGN',
}
],
date_Commenc: Date
})
Thanks for your help, It is my update in model
const mongoose = require('mongoose');
const Cours = mongoose.Schema({
name_Cours: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'UserCGN',
}
],
date_Commenc: Date
})
module.exports = mongoose.model('dataCours', Cours);
And in my $lookup
var coursM = await CoursModel.aggregate( [
{
$lookup:
{
from: "CGNModel",
localField: "_id",
foreignField: "cours",
as: "inventory_docs"
}
}
] )
And my data like that in dataCours
id:62ac815300878fa91f1549b9 name_Cours:Array 0:62a33ab745819dea27c8943d date_Commenc:2022-01-12T00:00:00.000+00:00
And in usercng, I have a id
_id:62a33ab745819dea27c8943d
But the result is empty