背景:
问题:
问题是,在获取用户模型时,未检索到任务。预计结果中会有一系列任务,但没有显示。
认证中间件
const verify = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(" ")[1];
try {
const decoded = await jwt.verify(token, process.env.JWT_ACCESS_KEY);
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ message: err });
}
} else {
res.status(403).json({ message: "Unauthorized" });
}
};
GetAll
如果用户授权,控制器任务:
const getAll = async (req , res) => {
const userId = req.user.payload._id;
if (userId) {
try {
const tasks = await userModel.findById(userId).populate("tasks");
res.status(200).json({msg: "", data: tasks});
console.log( req.user.payload.tasks);
console.log( userId);
} catch (err) {
console.log(err);
}
} else {
console.log(err);
}
}
用户架构:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
},
email: {
type: String,
unique: true
},
password: {
type: String,
},
tasks: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Task'
}],
})
module.exports = mongoose.model("User", UserSchema);
任务架构:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const TaskSchema = new Schema({
title: {
type: String,
},
status: {
type: Boolean,
default: false,
},
date: {
type: String,
default: new Date().toLocaleDateString().toString(),
},
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});
module.exports = mongoose.model("Task", TaskSchema);
数据库中的任务
{
"_id": "66147930903d1c2210adbeba",
"title": "React",
"status": false,
"date": "4/9/2024",
"owner": "66048c904a54bade1b0c9b26"
},
{
"_id": "661584b8f1fcbd39284091b2",
"title": "Angular",
"status": false,
"date": "4/9/2024",
"owner": "66048c904a54bade1b0c9b26"
},
我尝试了每个响应返回任务字段为空,据我了解模型之间的关系很好。
{
"msg": "User Data",
"data": [
{
"tasks": [],
"_id": "66048c904a54bade1b0c9b26",
"name": "Zezo",
"email": "[email protected]",
"password": "12345678",
"__v": 0
}
]
}
您应该将任务 ID 以数组形式存储在用户实体中,以便填充工作适合您
您的代码:
const tasks = await userModel.findById(userId).populate("tasks");
尝试:
const tasks = await userModel.findById(userId).populate(path:'tasks');