我正在尝试获取一个model方法(处理从CRUD的'Read'),该方法与我正在构建的node应用中的控制器一起工作,它将使用async/await在EJS模板中呈现从postgres数据库中提取的汽车列表。
const { query, pool } = require('./database');
module.exports = class Car {
constructor(
id, model_year, make, model, miles,
color, transmission, layout, engine_config, car_photo_url, car_price ) {
this.id = id;
this.model_year = model_year;
this.make = make;...
}
//method I'm working on
static fetchAll = async() => {
try {
let results= await query('SELECT * FROM cars');
console.log(results)
} catch (err) {
console.log(err)
}
//console.log(results.rows)
return results
}
控制器文件/方法(../controllers/admin):
const Car = require('../models/car');
exports.getVehicles = (req, res, next) => {
let rows = Car.fetchAll();
console.log(rows)
res.render('admin/vehicles', {
cars: rows,
pageTitle: 'Dealer Admin Page',
path: '/admin/vehicles'
});
}
使用express-promise-router
的路径/管理. js:
const Router = require('express-promise-router')
const express = require('express');
const adminController = require('../controllers/admin')
const router = new Router()
...
router.get('/vehicles', adminController.getVehicles);
...
})
module.exports = router;
使用EJS的前端模板:
<%- include('../includes/head.ejs') %>
</head>
<body>
<%- include('../includes/nav.ejs') %>
<main class="container py-5">
<% if (cars.length > 0) { %>
<section class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
<% for (let car of cars) { %>
<article class="col">
<div class="card shadow-sm">
<svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg>
<div class="card-body">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary">View</button>
<button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
</div>
<small class="text-muted">9 mins</small>
</div>
</div>
</div>
</div>
</article>
<% } %>
</section>
<% } else { %>
<h2>No Cars Found!</h2>
<% } %>
</main>
<%- include('../includes/end.ejs') %>
当我返回console.log(rows),
时,我不知道如何显示实际的行。在这种情况下,我如何使用async/wait语法显示从postgres数据库成功获取(?)的行?我应该用不同的方式重组吗?
1条答案
按热度按时间06odsfpq1#
我认为您应该在我的手机上用
static async fetchAll () { //Codes here }
Sry im编写该方法,然后执行此操作。