通过嵌套ID查找文档



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

我的路线:

  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      
   },

如果有人看到我的错误,我会很感激。

在引号中封闭嵌套路径。请参阅文档,其中说:

要在嵌入式/嵌套文档中的字段上指定查询条件,请使用点符号(" field.nestedfield")。

所以您的代码

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

应替换为

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

最新更新