我在玉器模板引擎中使用一个简单的循环来列出我的所有员工。 这是我的代码。
extends ../layout/main
block content
style(type='text/css').
.container.createEmployee {
float: left;
float: right;
width: 80%;
margin-top: 40px;
body
.container.createEmployee
h3
a(href='/employees/create') Create Employee
h1 Employee List
if employee.length > 0
for(var i=0 i<employee.length i++)
table.table.table-striped
thead
tr
th No#
th Employee Name
th Position
tbody
tr
td
a(href='/employees/show/ #{employee[i]._id}') #{employee[i].name}
//- td 1
//- td Moaiz pervaiz
td #{employee[i].position}
//- td Software Developer
div No employees found.
但是它显示了错误:
无法读取未定义的属性“ length”
我不知道为什么会出现此错误,请检查我的if
条件和for
循环。我是否正确使用它。请帮我。预先感谢。
这是我的控制器代码:
var mongoose = require("mongoose");
var Employee = require("../models/employee");
var employeeController = {};
employeeController.list = function(req, res) {
Employee.find({}).exec(function (err, employees) {
if (err) {
console.log("Error:", err);
}
else {
res.render("../views/employees/index", {employees: employees});
}
});
};
employeeController.show = function(req, res) {
Employee.findOne({_id: req.params.id}).exec(function (err, employee) {
if (err) {
console.log("Error:", err);
}
else {
res.render("../views/employees/show", {employee: employee});
}
});
};
employeeController.create = function(req, res) {
res.render("../views/employees/create");
};
employeeController.save = function(req, res) {
var employee = new Employee(req.body);
employee.save(function(err) {
if(err) {
console.log(err);
res.render("../views/employees/create");
} else {
console.log("Successfully created an employee.");
res.redirect("/employees/show/"+employee._id);
}
});
};
employeeController.edit = function(req, res) {
Employee.findOne({_id: req.params.id}).exec(function (err, employee) {
if (err) {
console.log("Error:", err);
}
else {
res.render("../views/employees/edit", {employee: employee});
}
});
};
employeeController.update = function(req, res) {
Employee.findByIdAndUpdate(req.params.id, { $set: { name: req.body.name, address: req.body.address, position: req.body.position, salary: req.body.salary }}, { new: true }, function (err, employee) {
if (err) {
console.log(err);
res.render("../views/employees/edit", {employee: req.body});
}
res.redirect("/employees/show/"+employee._id);
});
};
employeeController.delete = function(req, res) {
Employee.remove({_id: req.params.id}, function(err) {
if(err) {
console.log(err);
}
else {
console.log("Employee deleted!");
res.redirect("/employees");
}
});
};
module.exports = employeeController;