2017-12-13 16 views
1

更新されません:マングースfindByIdAndUpdateは()が返すオブジェクト/見つかったが、私はこのコードを見つけようとして、更新しています

exports.updatePlot = async (req, res) => { 
    let modifications = {}; 
    modifications.name = req.body.name; 
    modifications.grower = req.body.props.grower; 
    modifications.variety = req.body.props.variety; 
    modifications.planted = req.body.props.planted; 

    const id = req.body.props.id; 

    try { 
     const updatedPlot = await Plot.findByIdAndUpdate(
      id, 
      { $set: { modifications } }, 
      { new: true } 
     ); 
     res.json({ 
      updatedPlot 
     }); 
    } catch (e) { 
     return res.status(422).send({ 
      error: { message: 'e', resend: true } 
     }); 
    } 
}; 

は、私は私のリクエストボディにデータが含まれていることがわかります、私もいることがわかりますマングースこれは、それが更新さをプロットとしてログに記録するものであるため、オブジェクトを見つけることが、それを更新していません。

{"_id":"id string here","name":"old name",...all other properties...} 

私は私の要求が不正であると思いますか?誰も私の間違いを見ますか?

スキーマは次のようになります。

const plotSchema = new Schema(
    { 
     name: String, 
     ...other properties... 
    }, 
    { bufferCommands: false } 
); 

const ModelClass = mongoose.model('plot', plotSchema); 

答えて

1

あなたがこれまであなた$setオブジェクトを設定している:

$set: { 
    modifications: { 
     name: 'xxx', 
     grower: 'xxx', 
     variety: 'xxx' 
    } 
} 

ただし、あなたが望むものは次のとおりです。

$set: { 
    name: 'xxx', 
    grower: 'xxx', 
    variety: 'xxx' 
} 

このように、クエリでmodificationsに中括弧を削除してください:

const updatedPlot = await Plot.findByIdAndUpdate(
    id, 
    { $set: modifications }, 
    { new: true } 
); 
1

私はこの問題は、要求していると考え、これを試してみてください:

const updatedPlot = await Plot.findOneAndUpdate(
      {_id: id}, 
      modifications }, 
      { new: true } 
     ); 
関連する問題