我的数据存储在数据库中,集合名称为"用户";但是当我尝试从数据库中获取数据并尝试使用ejs进行显示时。有时它会显示找不到的数据,或者现在它显示forEach不是一个函数。甚至我也为此安装了所有必要的模块。
Here is my app.js code
app
.route("/newCandidate")
.get(function (req, res) {
res.locals.title = "New Candidate";
if (req.isAuthenticated()) {
console.log("registration done!");
res.render("newCandidate");
} else {
res.render("login");
}
})
.post(function (req, res) {
console.log("working candidate status");
var {
name,
email,
mobile,
offerIssued,
offerDate,
offerDoc,
packageOffered,
joiningBonus,
joiningDate,
isVerified
} = req.body;
console.log(req.body);
var data = req.body;
var isVerified = true;
User({
name,
email,
mobile,
offerIssued,
offerDate,
offerDoc,
packageOffered,
joiningBonus,
joiningDate,
isVerified,
}).save((err,data) =>{
if(err){
console.log(err);
}else{
console.log(req.body);
res.locals.title = "List Status";
res.render("listStatus");
}
});
});
app.get("/listStatus",function (req, res) {
var data = User(req.body).save(function(err,item){
if(err)console.log(err);
res.locals.title = "List Status";
res.render("listStatus",{item:data});
});
});
Here is my ejs file code
<% item.forEach(function(items){ %>
<tr>
<th scope="col"><%=items.name%></th>
<th scope="col"><%=items.email%></th>
<th scope="col"><%=items.mobile%></th>
<th scope="col"><%=items.offerIssued%></th>
<th scope="col"><%=items.offerDate%></th>
<th scope="col"><%=items.offerDoc%></th>
<th scope="col"><%=items.packageOffered%></th>
<th scope="col"><%=items.joiningBonus%></th>
<th scope="col"><%=items.joiningDate%></th>
<tr>
<% }); %>
在这个ejs文件中,我使用item来存储数据,并在js文件中创建对象和值,它可以从数据库中获取值。
问题是您的逻辑完全关闭。
当您调用User.save
时,您将返回一个表示您的用户的文档,即您调用的item
。然后,在回调中,您将发送回一个具有也称为item
的键的对象,并将其值设置为未定义的data
。
ejs中的代码抱怨forEach
不是一个函数,因为不知何故,您希望传递给模板的item
是一个数组,但它却是undefined
。
即使您在处理程序中将其更改为
res.render("listStatus",{item: item});
这可能是您想要做的,但您仍然无法调用forEach
,因为在这种情况下,item
将是单个用户(您刚刚保存的用户(,而不是用户阵列。
如果您想保存用户,然后呈现所有用户,则需要首先保存用户,等待保存,然后再次调用数据库以获取所有用户并将其发送到模板。
类似的东西
app.get("/listStatus", async function (req, res) {
// omitting error handling for the sake of clarity
await User(req.body).save();
const users = await User.find({});
return res.render("listStatus", { users });
}
// and in the ejs
<% users.forEach(function(user){ %>
...