簡體   English   中英

mongoose 如何僅在文檔中存在請求時更新文檔中的屬性?

[英]mongoose how to update properties in document only if they exist in request?

為了更新文檔,我通常這樣做......

  Model.findById(id)
.then((doc) => {
  doc.fName = req.body.fName
    ? req.body.fName
    : doc.fName;
  doc.lName = req.body.lName 
  ? req.body.lName
  : doc.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: " + result))
.catch((err) => res.send(err));

..它檢查該字段是否確實存在於正文請求中,否則它只是傳遞以前的值。

有沒有辦法只提供請求中的字段並讓它自己進行檢查,這樣如果一個字段不存在,它就不會刪除它? 像這樣...

  Model.someMethod(id)
.then((doc) => {
  doc.fName = req.body.fName
  doc.lName = req.body.lName
  return doc.save();
})
.then((result) => res.send(" Succesfully updated ! New data: " + result))
.catch((err) => res.send(err));

以這種方式使用它只會更新您在req.body中輸入的相同字段。其他字段將保持原樣。 NOT_ALLOWED字段中的變量將不會被更新。

const NOT_ALLOWED = ['_id'] //Just the same field will update which are not in this variable
     Model.findById(id).then((docs) => {
        Object.keys(req.body).map((key) => {

            if (NOT_ALLOWED.indexOf(key) === -1) {
                docs[key] = req.body[key]
            }

        })
        return docs.save()
    })
        .then((result) => console.log("Updated Data", result))
        .catch((err) => res.send(err));

您可以使用一個更新查詢來做到這一點。 首先,您可以根據req.body中的所有屬性構建更新配置。 然后,只需將該更新配置傳遞給更新查詢。 您還可以將{ new: true }作為第三個配置傳遞給更新查詢,因此將返回更新后的文檔。

let update = {};
if (req.body.fName) update.fName = req.body.fName;
if (req.body.lName) update.lName = req.body.lName;

Model.findByIdAndUpdate(id, update, { new: true })
  .then((result) => res.send(" Succesfully updated ! New data: " + result))
  .catch((err) => res.send(err));

暫無
暫無

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

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