Mongoose:使用 ObjectID 显示数据(或填充)

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

我正在编写一个 MERN Web 应用程序。此特定页面重点记录学生所记的过失。我有许多不同的模型可以相互交互,但在这种情况下我需要以下交互:

const demeritReportInstanceSchema = new mongoose.Schema({
    user : {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
...
})
const userSchema = new mongoose.Schema({
...
    fName: {
        type: String,
        required: true
    },
    lName: {
        type: String,
        required: true
    },
...
})

而当显示表格时,它当前看起来像这样:

用户 进攻日期 违规代码 惩罚官方
(这是用户ObjectID)65c5480f6b1bcdbcee2491aa 2024 年 2 月 2 日 1 另一个对象ID 另一个用户ObjectID

我需要它,它看起来像:

用户 进攻日期 违规代码 惩罚官方
l 名称,f 名称 2024 年 2 月 2 日 1 M11012 l 名称,f 名称

我一直在关注本教程:https://www.youtube.com/watch?v=CvCiNeLnZ00&t=12778s&ab_channel=DaveGray(参考:第 7 章),其中 Dave 有一个注释和用户模型(后端),如下所示:

const noteSchema = new mongoose.Schema({
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        },
...
})
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
})

在与我(前端)类似的表中显示用户名:

Note.js

        return (
            <tr className="table__row">
                ...
                <td className="table__cell note__username">{note.username}</td>

                ...
            </tr>
        )

NotesList.js

    if (isSuccess) {
        const { ids } = notes

        const tableContent = ids?.length
            ? ids.map(noteId => <Note key={noteId} noteId={noteId} />)
            : null

        content = (
            <table className="table table--notes">
                <thead className="table__thead">
                <tr>
                    ...
                    <th scope="col" className="table__th note__username">Owner</th>
                    ...
                </tr>
                </thead>
                <tbody>
                {tableContent}
                </tbody>
            </table>
        )
    }

任何帮助将不胜感激。

使用 {demerit.user} 为我提供了如上所示的用户 ID。使用 {demerit.user.fName},{demerit.user.lName} 在表的单元格中为我提供了“,”,并且不返回其属性。 我一直在研究如何使用 Mongoose 中的 Model.populate:https://mongoosejs.com/docs/populate.html 但我不知道在哪里放置填充查询 - 在前端,还是在带有模型的后端?

javascript mongoose mern mongoose-schema mongoose-populate
1个回答
0
投票

为了让您轻松实现这一点,我查看了教程,作者似乎将模型导入到控制器中并向数据库创建自定义查询函数,然后在每个路由处理程序中使用它们。因此,按照教程中采用的模式,您的代码可能类似于:

const Demerits = require('../models/Demerits'); //< or whatever this model is called
const User = require('../models/User');
const asyncHandler = require('express-async-handler');

const getAllDemerits = asyncHandler(async (req, res) =>{
   const demerits = await Demerits.find().populate('user').lean();
   if(!demerits){
      return res.status(400).json({message: 'No demerits found'});
   }
   res.json(demerits);
})

这里

populate('user')
是将
ObjectId
替换为完整的
User
文档,并允许您在前端访问
user.fName
user.lName

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