2016-06-14 83 views
0

以下代碼無法正常工作,我想在我的貓鼬findOne查詢後檢查是否定義了對象中的某個子文檔。檢查貓鼬對象是否包含子字段的函數

function cleanIfAny(social, value) { 
    var name = social + '.id'; 
    var query = {}; 
    query[name] = value; 

    User.findOne(query, function (err, found) { 
     if (err) console.log(err); 

     // if the account is already linked somewhere else 
     if (found) { 
      // detach it from there 
      found[social] = undefined; 

      // TODO Check if field in document is present 
      console.log(found.local + ' ' + found.google + ' ' + found.facebook); 
      console.log(isEmpty(found.local)+ ' ' + isEmpty(found.google) + ' ' + isEmpty(found.facebook)); 
      if(isEmpty(found.local) && isEmpty(found.google) && isEmpty(found.facebook)) { 
       console.log('no more account attached deleting'); 
       found.remove(); 
      } else { 
       console.log('ok unlink the account'); 
       found.save(function (err) { 
        if (err) console.log(err); 
       }) 
      } 
     } 

    }) 
} 

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

此代碼返回

{} { token: 'abcdefgh, name: 'FirstName LastName', id: '123456789', email: '[email protected]' } undefined 
false false false 
ok unlink the account 
預期與我的isEmpty(

取而代之的是

true false true 

但是我已經盡了功能這個範圍之外的一些簡單的變量和一切工作)功能。

回答

0

這可能會幫助你很多:

https://lodash.com/docs#isEmpty

保存你重新發明輪子所有的時間。

+0

我只是試着用lodash得到的結果在我的函數裏面是一樣的: 也許由mongoose返回的格式不是我期望的或者是在整個函數中有什麼不好的。 – melkir

+0

在我的情況下,typeof found,found.local,found.google和found.facebook是對象,即使未定義的 – melkir

+0

貓鼬文檔具有存儲實際mongo對象的'_doc'屬性。關鍵不是頂級。我認爲檢查'doc.property === undefined'應該可以。 – cdbajorin

相關問題