mongoose DBref数据未显示

7cwmlq89  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(77)

我有一个这样的mongoose模型模式,并且在MongoDB中已经有数据,我想根据所需的参数使用find()方法调用它。

const mongoose = require('mongoose');

const sessionSchema = new mongoose.Schema(
  {
    day: {
      type: String,
      required: true,
    },
    start_time: {
      type: String,
      required: true,
    },
    end_time: {
      type: String,
      required: true,
    },
    student: [
      {
        type: String,
        ref: 'USERS',
      },
    ],
    subject: {
      type: String,
      ref: 'SUBJECTS',
      required: true,
    },
    lecturer: {
      type: String,
      required: true,
    },
    classroom: {
      type: String,
      ref: 'CLASSROOM',
      required: true,
    },
  },
  { collection: 'SESSION' }
);

module.exports = mongoose.model('SESSION', sessionSchema);

字符串
我尝试用模型显示数据库的内容,如下所示:

const asyncHandler = require('express-async-handler');
const Session = require('../models/sessionModel');

const listSession = asyncHandler(async (req, res) => {
  const session = await Session.find({ 'student.$id': req.user._id });
  if (session) {
    res.status(200).json({ session });
  } else {
    res.status(404);
    throw new Error('User not found');
  }
});

module.exports = { listSession };


为什么当我运行代码时,它只显示“_id”和“lecturer”,用户名是正确的。没有显示所有具有ref的对象(student和subject)?
代码的预期结果是根据mongoose模式模型显示所有JSON

7vhp5slm

7vhp5slm1#

您应该populate引用:

await Session.find({ 'student.$id': req.user._id })
    .populate('student')
    .populate('subject')
    .populate('classroom')
    .exec();

字符串

相关问题