简体   繁体   中英

How to look up into db in mongo db using node js

I am learning NodeJS and Mongo Db and I got stuck. Could you please help me If you know solution?

I have 2 questions

1.)I have 2 collections in mongo db I tried to find out which projects user has. 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)

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.

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

在此处输入图片说明

在此处输入图片说明

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

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]}
    }
  }
])

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.

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