如何访问节点中数组中的对象

时间:2017-01-30 02:48:23

标签: node.js schema ejs

我正在尝试访问博客架构中的正文。我该怎么做。

架构:

var ArticleSchema = new mongoose.Schema({
  blog: [{
    topic: { type: String, unique: false, lowercase: true },
    body: {  type: String, unique: false, lowercase: true },
    tags: [ 'first', 'mongodb', 'express'],
    created: Date,
    modified: { type : Date, default : Date.now },
    state: {  type: String, unique: false, lowercase: true }
    }]
});

**

路由器

**

router.get('/blog/article/:postid', function (req, res, next) {
  Article.findById({ _id: req.params.postid }, function (err, article) {
    if (err) return next(err);
    res.render('main/publishedArticle', {
      article: article,
      message: req.flash('showing article ' + article.title)
    });
  });
});

**

publishedArticle.ejs

**

<h3><%= article.blog.body %></h3>

我未定义

1 个答案:

答案 0 :(得分:1)

您已将博客架构声明为对象数组(请注意,您已使用对象周围的[]作为博客项目)。如果这是故意的,那么您需要使用数组索引访问文章的各种 blog 元素(或使用循环迭代它们)。下面的代码段假定您的文章至少保存了一个博客条目:

<h3><%= article.blog[0].body %></h3>
相关问题