2013-05-10 62 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

相关问题