【问题标题】:trying to update single entry in mongodb using node js尝试使用节点 js 更新 mongodb 中的单个条目
【发布时间】:2021-11-11 03:37:50
【问题描述】:

const updateTask = async (req, res) => {
  const { id } = req.params;
  let update = {};
  if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
  if (req.body.taskContent) update.taskContent = req.body.taskContent;
  if (req.body.role) update.role = req.body.role;
  
  let task = await Task.updateOne(
    { taskId: id },
      {
        $set: {
        update,
       },
    },
    { runValidators: true }
  );
};

这是我更新数据库中数据的代码

如果我想更新单个数据,我正在尝试更新单个数据或密钥,但它没有更新任何东西

【问题讨论】:

  • 你确定id 是正确的吗?是简单的string 还是ObjectId
  • 用于插入 id 我正在使用 uniqid() 所以它是 String @eol

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

const updateTask = async (req, res) => {
  const { id } = req.params;
  let update = {};
  if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
  if (req.body.taskContent) update.taskContent = req.body.taskContent;
  if (req.body.role) update.role = req.body.role;
  
  let task = await Task.updateOne(
    { taskId: id },
      {
        $set: update,           
    },
    { runValidators: true }
  );
};

您所要做的就是删除大括号,它会像魅力一样工作$set : update

【讨论】:

    【解决方案2】:

    变量 Task 是什么?很抱歉,我并没有真正理解你的问题,所以你能更清楚地改述一下吗?

    如果没有,请小心,用户可能会将内容注入您的数据库。您应该使用mongo-sanitize 脚本。

    像这样:

    • 并检查您的 id 格式是否正确。如果在您的数据库中,它不在带有 MongoId 的 bjson 中。如果是这种情况,请不要犹豫,按照下面的方式转换您的 id。
    const sanitize = require('mongo-sanitize');
    const mongo = require('mongodb');  
    
    const updateTask = async (req, res) => {
      const { id } = req.params;
      let update = {};
      if (req.body.taskTitle) update.taskTitle = sanitize(req.body.taskTitle);
      if (req.body.taskContent) update.taskContent = sanitize(req.body.taskContent);
      if (req.body.role) update.role = sanitize(req.body.role);
      
      let task = await Task.updateOne(
        { taskId: mongo.ObjectId(sanitize(id)) }, // You can remove the mongo.ObjectId if your id is not a objectid.
          {
            $set: {
            update,
           },
        },
        { runValidators: true }
      );
    };
    

    【讨论】:

    • 如果有用户想要更新,我正在尝试更新单个值
    • 好的。所以,像这样使用你的 mongodb 变量:const mongo = require('mongodb'); id = new mongo.ObjectId(id); // Takes the real ID with bjson.
    • 仍然无法更新我的数据库,感谢您的尝试:)
    • 好的!对不起^^'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多