我正在尝试在引导模板中显示我的mongodb数据。
接口.js
var Software = require('../models/dbSoftware.js');
exports.show = (function(req, res) {
Software.find({Publisher: req.params.format}, function(error, softwares) {
res.render('searchpage', { searchText: req.params.format, softwares: softwares});
})
});
软件架构:
var mongoose = require('mongoose');
var softwareSchema = new mongoose.Schema({
SoftwareName: String
, Size: String
, Publisher: String
, Product: String
, Version: String
, Language: String
, License_Type: String
, Description: String
, License_Key: String
});
module.exports = mongoose.model('Software', softwareSchema);
搜索页面.ejs
<td><%= softwares.Product %></td>
这将返回未定义的值。任何软件*都返回"未定义"。
当我编辑搜索页面.ejs 时:
<td><%= softwares%></td>
输出为:
{ License_Key: 'computing', Description: 'Licensed', License_Type: 'English', Language: 'UNKNOWN', Product: 'Test Test', Publisher: 'Test', Size: '231.6MB', SoftwareName: 'Test.zip', _id: 5252c407d9b28d1e4c000001, __v: 0 }
//这是正确的
当使用 .find()
时,softwares
将是所有成功(error == null
)查询的Array
,无论找到的文档数量如何:
<%= softwares.length %>
<%= softwares[0].Product %>
如果您只需要一个文档,则需要改用.findOne()
:
Software.findOne({Publisher: req.params.format}, function(error, softwares) {
// ...
});
<% if (softwares != null) { %>
<%= softwares.Product %>
<% } %>
或者,您可以遍历softwares
:
<% softwares.forEach(function (software) { %>
<%= software.Product %>
<% }) %>