Mongoose / NodeJS – 来自数据库的string被检索,但被视为未定义

这是我现在的问题:

我查询findOne并填充我的数据库为了检索我的.EJS使用的string数组,但日志说,价值没有定义,但它给的价值的名称:“ string名称未定义”

我一定错过了什么..

这是用户架构:

 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}); }); }); }); 

根据你的评论

在Chrome浏览器中:“未捕获的ReferenceError:string名称未定义”(stringName =什么在表[0] .name)

尝试使用forEach运算符

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