node.js - 使用 Express 和 Mongoose 在 dom 中显示 Json 的问题
问题描述
我目前正在按照 Max Schwarzmüller 的这个 node js 教程开发我的第一个 node js express 项目,这是 node express mongoose,ejs。这真的是我的第一种方法,所以这里有很多糟糕的代码。
我无法在我的视图中呈现 json 对象,但我可以控制台记录它。我正在使用“位置”的模型,它是国家的集合。我使用 aa Locations Controller 来检索我在我的管理控制器上调用它的数据,我只是在渲染视图时传递它。
我不确定这种方法是否正确,我认为不是,所以如果有人给我关于这个分布的建议,我会很感激。
管理员控制器:
const locationsController = require('../controllers/locations');
exports.getAddConsejera = (req, res, next) => {
let message = req.flash('error');
if (message.length < 1) {
message = null
}
const countries = locationsController.getCountries();
res.render('admin/edit-consejera', {
pageTitle: 'Agregar Consejera',
path: '/admin/add-consejera',
editing: false,
errorMessage: message,
countries: countries
});
位置控制器:
const Location = require('../models/Location');
exports.getCountries = (req, res, next) => {
Location.find()
.then(countries => {
console.log(countries)
res.json(countries)
})
.catch(err => console.log(err))
};
定位模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const locationSchema = new Schema({
name: {
type: String,
required: true
},
});
module.exports = mongoose.model('Location', locationSchema);
错误
Cannot read property 'length' of undefined
看法:
<div class="col-lg-6 col-sm-12 col-md-12">
<label for="pais" class="form-label">Pais</label>
<select class="form-select" id="pais" name="pais" required>
<% for(i=0; countries.length> i; i++) { %>
<option>
<% countries._id %>
</option>
<% }%>
</select>
</div>
我相信原因与我的位置控制器有关。当我检索 json 我无法操作它时,它会正确迭代,但在我的 dom 中没有出现。只是空格。
期待任何答案,非常感谢!
解决方案
推荐阅读
- raspberry-pi - rosserial_server wifi 连接树莓派 ESP8266
- python - Selenium webdriver 有时找不到元素
- java - 在 Primefaces 中使用 Galleria 进行 imageRotateAndResize
- ffmpeg - 如何使用ffmpeg组合两个复杂的命令?
- laravel - laravel 获取会话数据并按最新排序
- gmail - 允许其他用户为我的电子邮件设置 gmail 过滤器
- python - 如何在 Elasticsearch 中对术语聚合结果进行分页
- c - scanf 格式的输入不适用于扫描的第一个字符
- javascript - 在 Array of Array 中查找对象
- asp.net-core - 发布后的 Asp net core web app 运行时错误