2017-01-30 94 views
0

我想要訪問博客模式內的主體。我該怎麼做。如何訪問節點中的數組中的對象

模式:

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

你宣佈你的博客模式作爲對象的數組(請注意,你」已經使用[]圍繞對象的博客項目)。如果這是故意的,那麼您需要使用數組索引訪問文章中的各種博客元素(或使用循環遍歷它們)。下面的代碼片段假設您的文章至少保存了一個博客條目:

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

謝謝,看起來很簡單 – CODI