簡體   English   中英

鏈接 collections MongoDB Nodejs Handlebars 的訪問文檔

[英]Access documents of linked collections MongoDB Nodejs Handlebars

我是一名業余 web 開發人員,我正在嘗試一個創建錯誤跟蹤平台的項目。 下面是我的儀表板的屏幕截圖。 標題為“報告者”的列顯示了報告錯誤的用戶的用戶 ID。 我的目標是不顯示用戶 ID,而是顯示用戶名。 在此處輸入圖像描述

我嘗試了幾次嘗試,但一直碰壁。 我使用的相關技術有Nodejs、Express、Handlebars和MongoDB

我有兩個 collections; 用戶和票。 我已經在 Ticket 集合中鏈接了 User 集合。

用戶收藏

const mongoose = require('mongoose')


const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }, 
    email: {
        type: String,
    },
    password: {
        type: String
    },
    userType: {
        type: String,
        required: true,
        default: 'Tester',
        enum: ['Tester', 'Admin']
    }
}, {timestamps: true})

const User = mongoose.model('User', UserSchema);
module.exports = User;

取票

const mongoose = require('mongoose')

const TicketSchema = new mongoose.Schema({
    title: {
        type: String,
        trim: true
    }, 
    tType: {
        type: String,
        enum: ['Development', 'Testing', 'Production']
    },
    status: {
        type: String,
        default: 'Open',
        enum: ['Open', 'Resolved', 'Closed']
    },
    priority: {
        type: String,
        enum: ['Low', 'Medium', 'High']
    },
    assignedTo: {
        type: String,
        enum: ['Julian', 'Jeremiah', 'Madani', 'Yassine', 'Nate']
    },
    description: {
        type: String,
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
}, {timestamps: true})

const Ticket = mongoose.model('Ticket', TicketSchema);
module.exports = Ticket;

我的索引頁面

const express = require('express')
const router = express.Router();
const { ensureAuth, ensureGuest } = require('../config/auth');
const Ticket = require('../models/Ticket');
const User = require('../models/User');

// Dashboard page
router.get('/dashboard', ensureAuth, async (req, res) => {
    try {
        const tickets = await Ticket.find({ user: req.user.id }).lean()
        const userName = await User.find({}, {_id: 1, name: 1}).lean() // Me trying to access the User collection
        if(tickets.user == userName._id) {
            res.render('dashboard.hbs', {
                name: req.user.name,
                userType: req.user.userType,
                tickets,
                userName
            })
        }
        
        console.log(userName)
    } catch (err) {
        console.log(err)
        res.render('error/500.hbs')
    }

})

module.exports = router;

最后,我的車把模板

{{#if tickets}}
    {{!-- {{#ifEquals tickets.user userName._id}} --}}
    {{#ifEquals userType "Admin"}}
        <table class="table table-hover">
        <thead>
            <tr class="table-active">
            <th scope="col">Ticket Number/ID</th>
            <th scope="col">Ticket Title</th>
            <th scope="col">Status</th>
            <th scope="col">Priority</th>
            <th scope="col">Reported by</th>
            <th scope="col">Assigned</th>
            <th scope="col">When</th>
            {{!-- <th scope="col"></th>

            <th scope="col"></th> --}}
            </tr>
        </thead>
        <tbody>
            {{#each tickets}}
                <tr class="taable-default">
                <th scope="row"><a href="/tickets/{{_id}}">{{_id}}</a></th>
                <td>{{title}}</td>
                <td><span class="dash-status">{{status}}</span></td>
                <td>{{priority}}</td>
                <td>{{user}}</td>
                <td>{{assignedTo}}</td>
                <td>{{formatDate createdAt 'MMMM Do YYYY, h:mm:ss a'}}</td>
                {{!-- <td></td>
                <td></td> --}}
                </tr>
            {{/each}}
        </tbody>
        </table>
...
...

首先,我使用 mongoose 方法findById()使用它的 Objectid 搜索 mongodb 文檔。 之后,我添加了user變量以使用dashboard.hbs呈現它

const express = require('express')
const router = express.Router();
const { ensureAuth, ensureGuest } = require('../config/auth');
const Ticket = require('../models/Ticket');
const User = require('../models/User');

// Dashboard page
router.get('/dashboard', ensureAuth, async (req, res) => {
    try {
        const tickets = await Ticket.find({ user: req.user.id }).lean()
        const user = await User.findById(tickets.user).lean() // Me trying to access the User collection
        if(tickets.user == user._id) {
            return res.render('dashboard.hbs', { // I would return here
                name: req.user.name,
                userType: req.user.userType,
                tickets,
                user
            })
        }
    } catch (err) {
        console.log(err)
        return res.render('error/500.hbs') // I would return here
    }

})

module.exports = router;

您需要在您的車把文件中更改的是簡單地請求user.name ,我們之前確定它來呈現dashboard.hbs模板:

{{#if tickets}}
    {{!-- {{#ifEquals tickets.user user._id}} --}}
    {{#ifEquals userType "Admin"}}
        <table class="table table-hover">
        <thead>
            <tr class="table-active">
            <th scope="col">Ticket Number/ID</th>
            <th scope="col">Ticket Title</th>
            <th scope="col">Status</th>
            <th scope="col">Priority</th>
            <th scope="col">Reported by</th>
            <th scope="col">Assigned</th>
            <th scope="col">When</th>
            {{!-- <th scope="col"></th>

            <th scope="col"></th> --}}
            </tr>
        </thead>
        <tbody>
            {{#each tickets}}
                <tr class="taable-default">
                <th scope="row"><a href="/tickets/{{_id}}">{{_id}}</a></th>
                <td>{{title}}</td>
                <td><span class="dash-status">{{status}}</span></td>
                <td>{{priority}}</td>
                <td>{{../user.name}}</td>
                <td>{{assignedTo}}</td>
                <td>{{formatDate createdAt 'MMMM Do YYYY, h:mm:ss a'}}</td>
                {{!-- <td></td>
                <td></td> --}}
                </tr>
            {{/each}}
        </tbody>
        </table>
...
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM