2017-05-02 43 views
0

我想使用Mongoose來返回有關用戶的信息以填充其配置文件。我一直使用findOne通過嵌入式文檔和.populate填充他們的評論列表以及基本的配置文件信息。我想通過計算好友陣列中有多少個對象來計算他們所擁有的朋友的數量。在貓鼬模式數組字段的findOne中計數

它看起來像聚合是這樣做的,但我怎麼能使用兩者?或者是否有一個簡單的方法在findOne查詢中進行計數?

var UserSchema = new Schema({ 
 
    username: String, 
 
    comments  : [{ type: Schema.Types.ObjectId, ref: 'Comment' }], 
 
    friends: [ 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t id: { type: Schema.Types.ObjectId, ref: 'User' }, 
 
\t \t \t \t \t \t permission: Number 
 
\t \t \t \t \t } 
 
    ] 
 
}) 
 
    
 
var User = mongoose.model('User', UserSchema); 
 
var Comment = mongoose.model('Comment', CommentSchema); 
 

 
app.get('/profile/:username', function(req, res) { 
 
User 
 
.findOne({ username: req.params.username }, 'username friends -_id') 
 
\t .populate({ 
 
\t \t path: 'current', 
 
\t \t model: 'Comment', 
 
\t \t select: 'comment author -_id date', 
 
\t \t populate: { 
 
\t \t \t path: 'author', 
 
\t \t \t model: 'User', 
 
\t \t \t select: 'username firstName lastName -_id' 
 
\t \t } 
 
\t }) \t 
 
.exec(function(err, user) { 
 
// 
 
}) 
 
)}

+0

爲什麼不使用user.friends.length? –

回答

0

如果與朋友陣列的用戶的回報,爲什麼不回來就user.friends.length?

如果你想算了算,用這個

User.aggregate([ 
    { 
     $match: { username: req.params.username } 
    }, 
    { 
     $unwind: "$comments" 
    }, 
    { 
     $lookup: { 
      from: "Comment", 
      localField: "comments", 
      foreignField: "_id", 
      as: "comments" 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$_id", 
      "friends": { "$first": "$friends"}, 
      "comments": { "$push": "$comments" } 
     } 
    }, 
    { 
     $project: { 
      _id: 0, 
      count: {$size: '$friends'}, 
      comments: 1, 
      username: 1 
     } 
    } 
]).exec() ... 
+0

,因爲如果我只需要計數時他們有很多實體,我會返回一個巨大的數組。如果我使用findOne和.populate來嵌入文檔,該怎麼辦?我可以使用聚合來做同樣的事嗎?或者我可以合併它們嗎? – totalnoob

+0

那麼,你不能使用聚合的方式。相反,您必須使用查找方法來獲取評論對象。我更新了我的答案。搜索查找,展開並將文檔分組:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/。 –

+0

另外,我看了你編輯的答案。看來你可能不需要聚合。只要你不填充朋友集合,它就會返回對象ID列表的數組,這是正常的。你可以返回那個長度。如果你仍然不想返回對象ID列表,你必須使用聚集,它可能需要更多時間來構建,因爲我能夠測試你的集合既不是視圖也不是所有的模式。 –