如何在 Express 和 mongoose 中建立两个模型之间的关系

问题描述 投票:0回答:1

响应中的“任务”字段始终为空,即使我知道数据库中有与用户关联的任务。

我检查了我的数据库记录,并且有任务分配给相关用户,因此问题似乎在于如何在 API 响应中获取或格式化数据。

我已经仔细检查了我的 Mongoose 模型,并确保正确定义了用户和任务之间的关系,并且每个响应都返回空任务。

enter image description here

认证中间件

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);

数据库中的任务

enter image description here

我尝试了每个响应返回任务字段为空,据我了解模型之间的关系很好。

enter image description here

node.js mongodb express mongoose
1个回答
0
投票

您编码:

const tasks = await userModel.findById(userId).populate("tasks");

尝试:

const tasks = await userModel.findById(userId).populate(path:'tasks');

您可以显示已保存用户的图片吗?

© www.soinside.com 2019 - 2024. All rights reserved.