html - Mongoose/NodeJS - 从数据库检索字符串但认为未定义

标签 html node.js mongodb express mongoose

这是我现在的问题:

我查询 findOne 并填充到我的数据库中,以便检索要在我的 .EJS 中使用的字符串数组,但日志显示该值未定义,但其给出的值名称为:“stringName 未定义”

我一定错过了什么..

这是用户架构:

var UserSchema = new mongoose.Schema({
    username: {  type: String, required: true, index: {  
    unique: true } },
    email: {  type: String, required: true, index: {unique: true } },
    password: {  type: String, required: true },
    tables: [{ type: Schema.Types.ObjectId, ref: 'Table' }],
    resetPasswordToken: String,
    resetPasswordExpires: Date,
    uuid: String,                
});

这是表架构:

var TableSchema = Schema({
    name: { type: String, required: true, index: { unique: true }},
    logos: [{ type: Schema.Types.ObjectId, ref: 'Logo'}],
});

这是我进行查询并将文档发送到 .ejs 页面的地方:

app.get('/dashboard/:uuid', function(req, res){
    if (req.user && userId != "")
    {
        var query = User.findOne({username:    req.user.username}).populate('tables').select('tables');

        query.exec(function (err, tables){
            if (err) return console.error(err);
            console.log (tables.tables[0].name); // Return the right string name
            res.render('./pages/dashboard.ejs', {username: req.user.username, tables: tables.tables});
        });
    }
    else
        res.redirect('/');
});

这是 ejs 中的脚本,应该在我的页面中呈现表名称:

 <script>
     $(document).ready(function (){
         <% for(var i = 0; i < tables.length; i++) {%>
         var newTab = "<a href=\"/work\"><div class=\"square\" style=\"display: inline-block\"><span style=\"margin-top: 50%; text-align: center\">" + <%=tables[i].name%> + "</span></div></a>";
         $(newTab).appendTo('.jumbotron');
         <%}%>

    });
</script>

如果你们能以我的方式启发一点那就太好了!

最佳答案

看看这个实现,这就是我查询模式的方式,在第一个示例中,我们重用了 req.user (好),在第二个示例中,我们进行了 2 个数据库调用(坏)。在您的示例中,您进行了 1 次数据库调用,但未填充表架构的 Logo 字段(不好)。

app.get('/dashboard/:uuid', function(req, res){
    // first example
    // no need to query users, you already have tables field
    if (!req.user) // what is userId, why you check it
        // add `err` checks
        return res.redirect('/');

    TableSchema
        .find({ _id: { $in: req.user.tables } })
        .populate('logos', 'url'); // Logo schema fields
        .exec(function(err, result_tables){
           res.render('./pages/dashboard.ejs', {username: req.user.username, tables: result_tables});
    });

    // or second example
    // if you still for some reason cannot use req.user.tables field
    // but strongly recommend to use first one
    User.findById(req.user._id, 'tables') 
        .exec(function (err, user_tables){
            // add `err` checks
            TableSchema.populate(user_tables, { path: 'logos', model: 'Logo' }, function (err, result_tables){
                // add `err` checks
                res.render('./pages/dashboard.ejs', {username: req.user.username, tables: result_tables});
            });
    });
});

根据您的评论

in chrome browser : " Uncaught ReferenceError: stringName is not defined " (stringName = what's in tables[0].name)

尝试使用 forEach 运算符

<script>
     $(document).ready(function (){
         <% tables.forEach(function(table){ %>
             var newTab = "<a ommited><%= table.name %></a>"; //notice: no `"`
             $(newTab).appendTo('.jumbotron');
         <% }) %>
    });
</script>

关于html - Mongoose/NodeJS - 从数据库检索字符串但认为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781838/

相关文章:

javascript - AngularJs - 模块已定义但仍然出现 "not available"错误

node.js - CompactToken 解析失败,错误代码 : 80049217 when using passport library to access Microsoft Graph API

node.js - 如何在 Node mongodb游标上批量处理文档而不超时

c# - MongoDB .NET 驱动程序 : AsQueryable() is not found

mongodb - 访问 Meteor 中的数据库对象

mongodb - 更新包含在 MongoDB 文档中的数组中的子文档

javascript - JQuery - 分离然后将一个项目附加到列表中 - 为什么这个简单的示例不起作用?

javascript - Pig Latin 在检查 JavaScript 中的元音时有缺陷的 If 语句

html - CSS 重新排序两个内联项

node.js - 如果 Upsert 是更新,如何撤消更新;如果 Upsert 是使用 Sequelize 插入,则如何删除