【问题标题】:How to access an object within an array in node如何访问节点中数组中的对象
【发布时间】:2017-06-15 04:00:27
【问题描述】:

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

架构:

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>

我越来越不确定

【问题讨论】:

    标签: node.js schema ejs


    【解决方案1】:

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

    <h3><%= article.blog[0].body %></h3>
    

    【讨论】:

    • 谢谢,看起来很简单