【问题标题】:Mongoose / NodeJS - String from db is retrieved but considered as not definedMongoose / NodeJS - 检索来自 db 的字符串,但认为未定义
【发布时间】:2016-10-13 09:43:02
【问题描述】:

这是我现在的问题:

我查询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>

如果你们能启发一下我的方法,那就太好了!

【问题讨论】:

  • app.get 路由中,您使用的是userId,但我看不出这是在哪里定义的?
  • 嗨,感谢您的回答@timothyclifford,userId 是使用 PassportJS 在其他地方定义的,那里一切正常
  • 你的日志语句是在哪里生成的?
  • 在 chrome 浏览器中:“未捕获的 ReferenceError:stringName 未定义”(stringName = 表中的内容[0].name)
  • 如果您在 tables 循环之前执行 console.logfor 循环,它被设置为什么?听起来它是空的......

标签: html node.js mongodb express mongoose


【解决方案1】:

看一下这个实现,这就是我查询模式的方式,在第一个示例中,我们重用 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});
            });
    });
});

根据您的评论

在 chrome 浏览器中:“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>

【讨论】:

  • 嘿!我尝试了您的第一个示例,结果与我的方式相同:-/ 使用 forEach: table.name 抛出错误“意外字符串” ...
  • @Naguib 再试一次 "&lt;a ommited&gt;&lt;%= table.name %&gt;&lt;/a&gt;"; //notice: no "
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 2022-12-06
  • 2020-01-31
相关资源
最近更新 更多