猫鼬-返回参考文档数组时如何选择特定字段?

时间:2019-03-15 23:40:42

标签: javascript node.js mongoose

预期结果:仅获取我引用的文档的“内容”属性。

我有一个猫鼬模型,我将过滤findOne结果。我使用populate方法获取对象架构的引用。

这是我的模特:

function getAuthorPost(username){
  return User.findOne({ username })
    .populate('posts').exec((err, posts) => { 

        console.log("posts: ", posts) 
    })
}

它返回:

{ posts:                                                        
   [ { author: [Array],                                                 
       _id: 5c8c31e2e204566cd7ecef4a,                                   
       content: 'April' },                                              
     { author: [Array],                                                 
       _id: 5c8c31e2e204566cd7ecef4b,                                   
       content: 'Great spring' },                                       
     { author: [Array],                                                 
       _id: 5c8c31e2e204566cd7ecef4c,                                   
       content: 'Natural path' },                                       
     { author: [Array],                                           
       _id: 5c8c31e2e204566cd7ecef4d,                                   
       content: 'Better cherry' },                                     
     { author: [Array],                                                 
       _id: 5c8c31e2e204566cd7ecef4e,                                   
       content: 'Water life' } ],                           
  _id: 5c8c255fed727439d6d5b860,                                        
  username: 'Frank',                                         
  __v: 1
 }

我只需要获取内容字段。

当我这样做

.populate('posts', {posts:"content"}).exec((err, posts) 

它向我返回以下ID:

{
  posts:                                                        
   [ { _id: 5c8c31e2e204566cd7ecef4a },                                 
     { _id: 5c8c31e2e204566cd7ecef4b },                                 
     { _id: 5c8c31e2e204566cd7ecef4c },                                 
     { _id: 5c8c31e2e204566cd7ecef4d },                                 
     { _id: 5c8c31e2e204566cd7ecef4e } ],                               
  _id: 5c8c255fed727439d6d5b860,                                        
  username: 'youmbo',                                                   
  __v: 1 
}    

我怎样才能只获得内容字段? 谢谢你的提示

0 个答案:

没有答案