javascript - Nodejs API 决定是创建还是更新

标签 javascript node.js rest api

我创建了一个nodejs API,您可以在其中通过POST推送新条目,如果该条目已经存在,它应该更新它。

现在我遇到一个问题,我通过 mongoose 的 findOne() 检查该条目是否已存在,但它不会触发更新功能。

这是代码:

通过 POST 的入口点:

    exports.create_a_status = function(req, res) {
  if(read_status(req.body.hostname)){
    console.log("update")
    update(req,res)
  }    
  else{
    var new_status = new Status(req.body);
    new_status.save(function(err, status) {
      if (err)
        res.send(err);
      history.create_a_history(req.body);
      res.json(status);
    });
  }
}

检查条目是否存在:

const read_status = function(hostname){
  Status.findOne({hostname: hostname},function(err,status){
    console.log(hostname)
    if (status){
      console.log(status)
      return status;
    }   
    return;
  })
}

和更新函数,但这不会从 create_a_status() 触发:

exports.update = function(req, res) {
    // Update a status identified by the hostname in the request
   Status.findOneAndUpdate({hostname: req.params.hostname}, req.body,{new:true})
    .then((updatedStatus) => {
      res.json(updatedStatus);
    })
    .catch((err)=>{
      res.send(err);
    });
};

提前致谢!

最佳答案

我解决了这个问题:

  exports.update_a_status = function(req, res) {
    // Update a status identified by the hostname in the request
   Status.findOneAndUpdate({hostname: req.body.hostname}, req.body,{upsert: true, new: true, runValidators: true})
    .then((updatedStatus) => {
      res.json(updatedStatus);
    })
    .catch((err)=>{
      res.send(err);
    });
};

重点是 findOneAndUpdate() 函数中的选项,其中我没有设置 upsert: true 这意味着如果它没有通过主机名找到条目,它只会创建它。

关于javascript - Nodejs API 决定是创建还是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915195/

相关文章:

javascript - 动态网站宽度

javascript - 无法启动 Node 应用程序(server.js,可能是 Babel 问题?)

javascript - 在查询 mongodb 之前,如何检查 mongo db 中是否存在字段?

javascript - 如何使用 Q 库同时将 Node 异步函数转换为 Promise?

node.js - NodeJS API 通过 ID 获取。如何检测未找到的项目?

rest - 是否有 Google Cloud 项目 ID 的受限词列表?

php - file_get_contents() : SSL operation failed with code 1, 无法启用加密

sencha touch 2 中的 HTTP 请求

javascript - 如何将 border-radius 等 css 属性与可转换对象一起使用

javascript - 调整窗口大小时防止 Canvas 清除