MongoDB - 如何显示用户登录的所有任务



所以我有 3 个模型:用户、项目和任务......

我想在我的仪表板中显示登录用户的用户项目的所有任务,但是发生的事情是,当我以例如"user1"登录时,它会显示集合中的所有任务,并且"user2"显示集合中的所有任务......我只想显示登录用户的任务。.

我的用户不包含任务,只包含项目,我认为我可以使用聚合查找来执行此操作,但我不知道如何使用它,也不知道这是否是最好的方法

用户型号:

let mongoose = require("mongoose");
let passportLocalMongoose = require("passport-local-mongoose");
let UserSchema = new mongoose.Schema({
username: String,
password: String,
companyname: String,
companyimageURL: String,
projects: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Project'
}]
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

项目型号:

let mongoose = require("mongoose");
let projectSchema = new mongoose.Schema({
projectname: String,
typeofproject: String,
imageURL: String,
dateMonthFrom: String,
dateYearFrom: String,
dateMonthTo: String,
dateYearTo: String,
tasks: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tasks'
}],
user: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
})
module.exports = mongoose.model('Project', projectSchema);

任务模型:

let mongoose = require("mongoose");
let taskSchema = new mongoose.Schema({
tasktitle: String,
taskcomment: String,
project: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Project'
}]
})
module.exports = mongoose.model('Tasks', taskSchema);

我的服务器端

exports.render_all_tasks = (req, res) => {

User.aggregate([
{
$lookup:{
from: 'projects',
localField: 'projects',
foreignField: 'tasks',
as: 'user'
}
}
]).exec((err) => {
if(err) {
console.log(err);
}
Task.find({}).populate('project').exec((err, tasks) => {
if(err) {
console.log(err);
}
res.send(tasks);
});   
});
};

用户集合:

{
_id: ObjectId("..."),
projects: [ 0: ObjectId("..."), 1: ObjectId("...")],
username: "user1",
companyname: "company1",
companyimageURL: "..."
}

项目集合:

{
_id: ObjectId("..."),
tasks: [ 0: ObjectId("..."), 1: ObjectId("...")],
user:  [ 0: ObjectId("...")],
projectname: "project1",
typeofproject: "type1",
imageURL: "..."
}

任务集合:

{
_id: ObjectId("..."),
project: [ 0: ObjectId("..."),
tasktitle: "Task 1"
}

可以直接查询项目集合以获取登录用户的任务。

类似的东西

Project.aggregate([
{"$match":{"user":logged in user}},
{"$lookup":{
"from":"tasks",
"localField":"tasks",
"foreignField":"_id",
"as":"tasks"
}}
])

您可以在 3.6 中使用以下聚合从用户集合进行查询。这将为每个用户获取所有项目中的所有任务。

User.aggregate([{
"$lookup":{
"from":"projects",
"let":{"projects":"$projects","user":"$_id"},
"pipeline":[
{"$match":{
"$expr":{
"$and":[
{"$in":["$_id","$$projects"]},
{"$in":["$$user","$user"]}
]
}}
},
{"$lookup":{
"from":"tasks",
"localField":"tasks",
"foreignField":"_id",
"as":"tasks"
}}
],
"as":"project-tasks"
}
}])

最新更新