2016-07-25 30 views
1

這裏的MongoDB光標是從我的Node.js後端代碼:遍歷從總

app.get('/getpossibleconnections', auth, function(req, res){ 
    if (req.authenticated == false){ 
     res.send("Your session has expired."); 
    } else { 
     User.aggregate([ 
      { $match: { _id: { $nin: req.decoded.username.connections } } }, 
      { $sample: { size: 10 } }, 
     ]).next(function(err, docs) { 
      console.log("horray"); 
     }); 
    } 
}); 

我試着更換next()toArray()each()的建議在這裏:

http://mongodb.github.io/node-mongodb-native/2.0/tutorials/aggregation/

然而,我每次收到相同的錯誤:

TypeError: User.aggregate(...).next is not a function

爲什麼我不能用任何函數遍歷返回的文檔?

是否因爲User不是集合?

+0

一個可能的解決方案是簡單地通過回調和迭代結果 – Radioreve

+0

什麼是變量「用戶」被分配給?在提供的鏈接中,他們連接到一個數據庫,然後將一個變量設置爲該數據庫中的一個集合,你是否也這樣做? – devonJS

+0

@devonJS用戶是一個模型,但我使用貓鼬,從我所瞭解的貓鼬中自動將集合與每種模型類型相關聯。 – db2791

回答

3

試試這個:

var cursor = User.aggregate([ 
    { $match: { _id: { $nin: req.decoded.username.connections } } }, 
    { $sample: { size: 10 } }, 
]).cursor().exec(); 

cursor.each(function(err, doc) { 
    //do something with doc 
}); 

貓鼬不同的方式處理的骨料光標對象比MongoDB的原生,你在你的鏈接發佈。更多的信息在這裏:mongoose aggregate cursor documentation

+0

你是一個絕對的傳奇。非常感謝 – db2791