简体   繁体   English

mongoose 如何仅在文档中存在请求时更新文档中的属性?

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

In order to update a document i usually do as such...为了更新文档,我通常这样做......

  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));

..which checks if the field actually exists in the body request,otherwise it just passes the previous value. ..它检查该字段是否确实存在于正文请求中,否则它只是传递以前的值。

Is there a way to just provide the fields in the request and let it do the check for itself so if a field does not exist,it will not delete it?有没有办法只提供请求中的字段并让它自己进行检查,这样如果一个字段不存在,它就不会删除它? like so...像这样...

  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));

Using it in this way will only update the same field that you enter in the req.body .Other fields will be as it is.以这种方式使用它只会更新您在req.body中输入的相同字段。其他字段将保持原样。 Which is in the fields NOT_ALLOWED variable will not be updated.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));

You can do that with one update query.您可以使用一个更新查询来做到这一点。 First, you can construct the update config based on all the properties from the req.body .首先,您可以根据req.body中的所有属性构建更新配置。 Then, just pass that update config to the update query.然后,只需将该更新配置传递给更新查询。 You can also pass { new: true } as third config to update query, so the updated document will be returned.您还可以将{ 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