2017-06-16 28 views
1

當我的聚合沒有發現任何東西,數據是[]時,它仍然可以解決我的功能。如何檢查你是否真的從你的聚合中得到結果

我該如何檢查我的聚合實際上是否找到了一些東西?

if (!data) {不工作

usersTable.aggregate (
    { 
     $match:{ 
      _id: UserID 
     } 
    } 
,function (err, data) { 
    if (err) { 
     throw new Error('findUser: ' + err); 
    } else { 
     console.log("found: " + JSON.stringify(data, null, 4)); 
     if (!data) { 
      throw new Error('ERR: Unknown userID in call of newBooking'); 
     } 
     resolve("OK"); 
    }; 
}); 
+0

你使用的是mongodb嗎?如果是,哪個版本? – trincot

+0

最新版本3.4 – torbenrudgaard

回答

0

解決它像這樣,if (!data) {永遠不會起作用,因爲即使蒙戈返回一個空的對象,它仍然是一個對象。

相反,我發現這個功能

function isEmpty(obj) { 
    return Object.keys(obj).length === 0; 
} 

所以,現在我可以用if (isEmpty(data)) {和它完美的作品。

相關問題