检索mongoose文档元素时返回“未定义”

时间:2013-10-14 18:23:36

标签: node.js mongodb twitter-bootstrap mongoose

我试图在bootstrap模板中显示我的mongodb数据。

api.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);

searchpage.ejs

<td><%= softwares.Product %></td>

返回未定义的值。任何软件。*返回'undefined'。

当我将searchpage.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 } 

//哪个是正确的

1 个答案:

答案 0 :(得分:0)

使用.find()时,softwares对于所有成功(Array)查询都是error == null,无论找到多少文档:

<%= softwares.length %>
<%= softwares[0].Product %>

如果您只想要一个文档,则需要使用.findOne()代替:

Software.findOne({Publisher: req.params.format}, function(error, softwares) {
    // ...
});
<% if (softwares != null) { %>
    <%= softwares.Product %>
<% } %>

或者,您可以iterate over softwares

<% softwares.forEach(function (software) { %>
    <%= software.Product %>
<% }) %>