2016-07-21 5 views
1

私はdataToChangeオブジェクトに含まれるすべてのフィールドを更新したいと思いますが、何らかの理由でupdate()にキー名を渡すことができません。メソッドは外部から取得せず、データベースのオブジェクトの "key" 。どうしたらいいですか? ${key}を使用しようとしましたが、エラーと見なされます。Mongooseのupdate()メソッドにフィールド名を渡す方法は?

changeUserInfoFashion = function (id, dataToChange, res, callback) { 
     //var id = id; 
    _.forIn(dataToChange, function (value, key) { 
     key.toString(); 
     console.log('I AM GOING TO UPDATE ' + key + " WITH " + value); 
     User.update(
      {"_id": id}, 
      //Here I need to pass key --> 
      {key: value}, 
      function (err, results) { 
       console.log(results); 
       if (err) { 
        return callback(); 
       } 
       return res.json({success: true, msg: key + ' changed.'}).status(200); 
      }); 
    }); 
}; 

dataToChangeのExamplaeは動作しません

{ 
name: 'Baby', 
age: 32 
} 

答えて

2

オブジェクトを反復処理し、各フィールドを更新する必要はありませんが、あなたは$set演算子を使用することができます。

changeUserInfoFashion = function (id, dataToChange, res, callback) {  
    User.update(
     { "_id": id }, 
     { "$set": dataToChange }, 
     function (err, results) { 
      console.log(results); 
      if (err) { return callback(); } 
      return res.json({ 
       success: true, 
       msg: JSON.stringify(dataToChange) + ' changed.' 
      }).status(200); 
     } 
    );  
}; 
1

です。それにキーと値を空のオブジェクトを作成し、割り当てます。次のように

_.forIn(dataToChange, function (value, key) { 
    key.toString(); 
    console.log('I AM GOING TO UPDATE ' + key + " WITH " + value); 
    var updateData = {}; 
    updateData[key] = value; 
    User.update(
     {"_id": id}, 
     //Here I need to pass key --> 
     updateData, 
     function (err, results) { 
      console.log(results); 
      if (err) { 
       return callback(); 
      } 
      return res.json({success: true, msg: key + ' changed.'}).status(200); 
     }); 
}); 
1
changeUserInfoFashion = function (id, dataToChange, res, callback) { 
     //var id = id; 
     User.update(
      {"_id": id}, 
      dataToChange, 
      function (err, results) { 
       console.log(results); 
       if (err) { 
        return callback(); 
       } 
       return res.json({success: true, msg: key + ' changed.'}).status(200); 
      }); 
}; 
関連する問題