代码之家  ›  专栏  ›  技术社区  ›  JimB814

按嵌套ID查找文档

  •  1
  • JimB814  · 技术社区  · 8 年前

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

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

    1 回复  |  直到 8 年前
        1
  •  3
  •   Benjamin    8 年前

    将嵌套路径括在引号中。看见 documentation

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

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

    应替换为

    Article.find( {"author.id": req.params.id} )
    
    推荐文章