按嵌套ID查找文档

时间:2017-09-17 15:34:55

标签: node.js mongodb mongoose

尝试使用嵌套ID为(author.id)的作者识别正确的语法来检索文章。抛出SyntaxError,无法找到解决方案。

我的路线:

  router.get('/articles/authors/:id', function(req, res){

      Article.find( {author.id: req.params.id} ).sort( {createdAt: -1} ).exec(function(err, articles){
        if(err){
           console.log(err);
           return req.flash('error', 'Unable to find author.');
        } else {
           console.log(articles);
           res.render('authors/', {
              articles: articles,
              pagetitle: 'Articles by '
           });
        }
     });
  });

我的文章的作者部分是:

   author:
   {
      id:
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"    
      },
      username: String, 
      name: String      
   },

如果有人能看到我的错误,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

将嵌套路径括在引号中。请参阅documentation,其中包含:

  

要在嵌入/嵌套文档中的字段上指定查询条件,请使用点表示法(“field.nestedField”)。

所以你的代码

tf.estimator.Estimator

应替换为

Article.find( {author.id: req.params.id} )