简体   繁体   English

如何在 mongodb 和 nodejs 中使用 $lookup,因为我的是空的

[英]How use the $lookup in mongodb and nodejs because mine is empty

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 dans UserCGN

username:"njatotianafiononana@gmail.com" cours:"Anglais"用户名:“njatotianafiononana@gmail.com” 课程:“英语”

et dans le dataCours et dans le dataCours

name_Cours:"Anglais" date_Commenc:2022-01-12T00:00:00.000+00:00 name_Cours:"Anglais" date_Commenc:2022-01-12T00:00:00.000+00:00

Et voici mon code pour récuperer 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.在我的表中,inventory_docs 始终为空。 Please, help me请帮我

These two models should be connected.这两个模型应该连接起来。 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"这样您就可以使用foreignField: "_id"进行lookup

const Cours = mongoose.Schema({
    name_Cours: [
      { 
         type: mongoose.Schema.Types.ObjectId,
         ref: 'UserCGN',            
      }
    ],
    date_Commenc: Date
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM