简体   繁体   English

如何使用节点js在mongo db中查找db

[英]How to look up into db in mongo db using node js

I am learning NodeJS and Mongo Db and I got stuck.我正在学习 NodeJS 和 Mongo Db,但我被卡住了。 Could you please help me If you know solution?如果你知道解决方案,你能帮我吗?

I have 2 questions我有2个问题

1.)I have 2 collections in mongo db I tried to find out which projects user has. 1.) 我在 mongo db 中有 2 个集合,我试图找出用户拥有哪些项目。 For example michaela has projects :nodejs, test2 jasmin has projects: test2 (I don't want to know who are coders for current project but I want to know what are projects for current user)例如michaela有项目:nodejs,test2 jasmin有项目:test2(我不想知道谁是当前项目的编码人员,但我想知道当前用户的项目是什么)

data what I want to get should look something like this我想要得到的数据应该是这样的

[{
  id: "some value"
  username: "michaela"
  email:"some value"
  password:"some value"
  projects:"[{
     project_name:"node js"
     project_description:"learn node js"
     deadline:"2021-11-12"
     status:"todo" 
  },
  {
     project_name:"test2"
     project_description:"learn node js"
     deadline:"2021-11-12"
     status:"todo" 
  }]
  },
  id: "some value"
  username: jasmin"
  email:"some value"
  password:"some value"
  projects:"[
  {
     project_name:"test2"
     project_description:"learn node js"
     deadline:"2021-11-12"
     status:"todo" 
  }]

}]

I don't understand exactly how look up works.我不明白查找究竟是如何工作的。 I tried following example(test) but it doesn't work我尝试了以下示例(测试)但它不起作用

I also don't understand how to connect 2 db for example allMembers and all projects I merged into one array but I don't think this is correct way how to do it.我也不明白如何连接 2 db,例如 allMembers 和我合并到一个数组中的所有项目,但我认为这不是正确的方法。

this is my model这是我的模型

const usersCollection = require('../db').db().collection("users")
const projectsCollection = require('../db').db().collection("projects")

Team.prototype.getAllMembers = function(){
    return new Promise (async (resolve, reject) => {
        try{
            let allMembers = await usersCollection.find({}).toArray()
            let allprojects = await projectsCollection.find({}).toArray()
                        let test = await  usersCollection.aggregate([
                {$lookup: {from: "projects", localField: "username", foreignField: "coder", as: "projects"}},
                {$project: {
                    username:1, 
                    projects:{
                         name:{$arrayElemAt: ["$projects.project_name", 0]},
                         description:{$arrayElemAt: ["$projects.project_description", 0]},
                    },
                    email:1,
                    password:1,
                  }}
              ]).toArray()
              console.log("test", test)
            let arr3 = [...allMembers, ...allprojects]
            resolve(arr3)
        }catch{
            reject()
        }
    })
}


this is my controller这是我的控制器

exports.home = function(req, res) {
    //when user is log in
    if (req.session.user) {
     let teamMember = new Team(req.body)
      teamMember.getAllMembers().then((data)=>{
        console.log("members data", data)
          if(data){
            res.render('members', {data: data })
          }else{
            res.send("on this page are no data")
          }
      }).catch((err)=>{
          res.send("problem")
      }) 
      //when user is not log in, flash tie errory z db automaticky vymaze po pouziti
    } else {
      res.render('login', {errors: req.flash('errors'), regErrors: req.flash('regErrors')})
    }
  }


and this is how it looks in db这就是它在 db 中的样子

在此处输入图片说明

在此处输入图片说明

Thank you in advance先感谢您

I think you should aggregate on user collection like this match user name and then project first element of projects lookup in here put project to projects field我认为您应该像这样匹配用户名那样聚合用户集合,然后在此处将项目查找的第一个元素投影到项目字段中

db.users.aggregate([
  {
    $match: {
      username: "jasmin"
    }
  },
  {
    "$lookup": {
      "from": "projects",
      "localField": "username",
      "foreignField": "coder",
      "as": "projects"
    }
  },
  {
    "$project": {
      username: 1,
      email:1,
      password:1,
      projects: 1
    }
  }
])

https://mongoplayground.net/p/U6hNw2WdQLE https://mongoplayground.net/p/U6hNw2WdQLE

if you want to get all data with just first project in that use this如果您只想在第一个项目中获取所有数据,请使用此

db.users.aggregate([

  {
    "$lookup": {
      "from": "projects",
      "localField": "username",
      "foreignField": "coder",
      "as": "projects"
    }
  },
  {
    "$project": {
      username: 1,
      email:1,
      password:1,
      projects:{$arrayElemAt: ["$projects", 0]}
    }
  }
])

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

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