我是一名努力使我的mongodb对象显示在浏览器中的开发人员。我认为我的查询运行正常,但是由于某些原因,网页上的forEach循环未显示我的数据。
这是我的app.js代码:
const express = require('express'),
methodOverride = require('method-override'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
expressSanitizer = require('express-sanitizer'),
app = express();
mongoose.connect('mongodb://localhost:27017/sale', {useNewUrlParser: true});
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressSanitizer());
app.use(methodOverride('_method'));
//mongoose model config
var saleSchema = new mongoose.Schema({
name: String,
addrLine1 : String,
addrLine2 : String,
City: String,
State: String,
Date: {type: Date},
saleCategories: {type: String}
});
var Sale = mongoose.model('Sale', saleSchema);
var categorySchema = new mongoose.Schema({
type: {type: String}
});
var Category = mongoose.model('Category', categorySchema);
//RESTful Routes
app.get('/', (req, res) => {
res.redirect('/sales');
});
//Index
app.get('/sales', (req, res) => {
Sale.find({}, (err, sales) => {
if(err){
console.log("ERROR ON INDEX!");
} else {
res.render('index', {sales: sales});
}
});
});
这是我的ejs文件:
<% include partials/header %>
<h1>Sales Index page</h1>
<% sales.forEach((sale) => { %>
<p><%= sale.name %></p>
<% }); %>
<% include partials/footer %>
这是我的mongodb的销售合集:
> db.sale.find({}, {name: 1, _id: 0})
{ "name" : "Craig Test Sale" }
{ "name" : "McCauley Test Sale" }
我希望我的ejs文件列出销售集合中每个项目的名称字段,但是除了页眉,页脚和<h1>
外,我什么也没得到。