所以我有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"
}
答案 0 :(得分:1)
您可以直接查询项目集合以获取登录用户的任务。
类似
interface iFooArgs{
text: string;
bypass?: boolean;
snapshot?: boolean;
}
function foo(args: iFooArgs): string {
if(args.bypass){
return 'bypass';
}
if(args.snapshot){
return 'snapshot';
}
return args.text;
}
console.debug(foo({text: 'test'}));
console.debug(foo({text: 'bypass?', bypass: true}));
console.debug(foo({text: 'snapshot?', snapshot: true}));
OR
您可以在3.6中使用以下聚合从用户集合中进行查询。这将为每个用户获取所有项目中的所有任务。
Project.aggregate([
{"$match":{"user":logged in user}},
{"$lookup":{
"from":"tasks",
"localField":"tasks",
"foreignField":"_id",
"as":"tasks"
}}
])