2013-05-10 66 views
0

我在查詢用戶對象並對比傳入postdata(jsObject)中的項目執行一系列更新。我想知道如何從對象中完全刪除一個項目...特別是一個Date對象(user [0] .birthDate)...在我保存更新的用戶對象之前。如何從NodeJS/Mongo服務中的對象中刪除項目

orm.User.find({ appId: appId, facebookUsername:usersFBUsername}).exec(function (error, user) { 
     if (error) { 
      console.log('Error in User Query: ' + error); 
     } 
     else if(Object.keys(user).length > 0) { 

      if(jsObject.name != null) 
       user[0].name = jsObject.name; 

      if(jsObject.email != null) 
       user[0].emailAddress = jsObject.email; 

      if(jsObject.birthDate != null && jsObject.birthDate.length > 0) { 
       user[0].birthDate = jsObject.birthDate; 
      } 
      else { 
       console.log('delete it'); 
       //orm.User.update({_id:user._id}, {$pull:{birthDate:1}}); 
       //delete user[0].birthDate; 
      }    
     } 

     user[0].save(function (error) { 
       if (error != null) { 
        console.log('An error has occurred while saving user:' + error); 
        response.end(results.getResultsJSON(results.ERROR, error)); 
       } 
       else { 
        console.log(' [User Successfully Updated]'); 
        response.end('{ "success": ' + JSON.stringify(user[0]) + ' }'); 
       } 
      }); 
     }); 

您可以在評論代碼中看到我所做的一些未成功的嘗試。我甚至在完成保存後給了這個試試,這也沒有工作:

orm.User.update({appId: appId, facebookUsername:usersFBUsername},{$pull:{birthDate:deleteBirthDate}}) 
       .exec(function(error){ 
        if(error) { 
         console.log('oh well: ' + error); 
        } 
        else { 
         console.log('maybe maybe'); 
        } 
       }); 

我欣賞任何建議。

克里斯

+0

刪除(field.attribute)將刪除屬性字段,其價值 – 2013-05-11 03:27:48

+0

@AsyaKamsky:這確實很遺憾不工作(可能是因爲我在使用Mongoose?)。 – ninehundredt 2013-05-12 15:35:28

+0

我曾經以爲你回到了完整的對象,並想從json文檔中刪除該字段。如果您在更新時嘗試取消設置,則下面的答案是正確的。 – 2013-05-12 15:37:49

回答

1

$pull是從陣列中移除值,但你可以使用$unset

orm.User.update(
    {_id  : user._id}, 
    { $unset : { birthDate : 1 }}, 
    function(err, numAffected) { 
    ... 
    } 
); 
+0

這工作完美。感謝您的幫助! – ninehundredt 2013-05-12 15:36:05

相關問題