簡體   English   中英

如何在數據更改時更新MongoDB文檔?

[英]How to update MongoDB document only when data changed?

我正在構建CRUD應用程序的后端。 我目前有一個用於/diagrams/update:id的POST路由設置,我可以使用Postman發送的正文文本覆蓋MongoDB文檔。

我可以成功更新文檔,但是當我嘗試更新文檔中的一個數據時,其他所有內容都會被刪除。

我希望我的代碼1)檢測我嘗試更改的內容是否與數據庫中的數據不同,2)僅當它不同時,更新記錄,3)如果沒有更改,請不要更新並保留數據庫中的當前數據。

我試着做點什么

if (diagram.name !== req.body.name) {
diagram.name = req.body.name}

但那意味着我必須為每一次改變都寫出那個邏輯。

server.js

router.route('/diagrams/update/:id').post((req, res)=> {
  mySchema.findById(req.params.id, (err, diagram) => {
    if (!diagram)
      return next(new Error('Could not load doc!'))
    else {

// I tried something like
// if (diagram.name !== req.body.name) {
// diagram.name = req.body.name}
// but that only works one at a time

      diagram.name = req.body.name;
      diagram.creator = req.body.creator;
      diagram.customer = req.body.customer;

      diagram.save().then( diagram => {
        res.json('Update done!')
      }).catch(err => {
        res.status(400).send('Update faileddddd')
      })
    }
  })
})

MySchema.js

const mongoose = require( 'mongoose');
const Schema = mongoose.Schema;

let mySchema = new Schema({

    name: {
        type: String
    },
    creator: {
        type: String
    },
    customer: {
        type: String
    }
}, {collection: `fivo`})

你可以做這樣的事情。 只需傳遞要在對象中更新的所有值。

let update = async (userId, properties) => {
  let user = await Users.findOne({ _id: userId });

  // Update all properties.
  for(property in properties) {
    user[property] = properties[property];
  }

  user = await user.save();
  return user;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM