[英]How to look up into db in mongo db using node js
我正在学习 NodeJS 和 Mongo Db,但我被卡住了。 如果你知道解决方案,你能帮我吗?
我有2个问题
1.) 我在 mongo db 中有 2 个集合,我试图找出用户拥有哪些项目。 例如michaela有项目:nodejs,test2 jasmin有项目:test2(我不想知道谁是当前项目的编码人员,但我想知道当前用户的项目是什么)
我想要得到的数据应该是这样的
[{
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"
}]
}]
我不明白查找究竟是如何工作的。 我尝试了以下示例(测试)但它不起作用
我也不明白如何连接 2 db,例如 allMembers 和我合并到一个数组中的所有项目,但我认为这不是正确的方法。
这是我的模型
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()
}
})
}
这是我的控制器
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')})
}
}
这就是它在 db 中的样子
先感谢您
我认为您应该像这样匹配用户名那样聚合用户集合,然后在此处将项目查找的第一个元素投影到项目字段中
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
如果您只想在第一个项目中获取所有数据,请使用此
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.