使用Node.js更新MongoDB中的表单值时出错

时间:2018-09-06 12:09:19

标签: node.js mongodb express mongoose put

后删除选项可以正常工作,但是放置不起作用,它可以成功更新,但是具有 function String(){[native code]} 值。

controller.ts

A,B
1,11
2,19
3,18
4,19
5,18
6,12
7,12
8,19
9,13
10,19

model.ts

library(ggplot2)
g = qplot(`A`, data = dataset)
g

2 个答案:

答案 0 :(得分:1)

您需要阅读需求主体,然后使用这些值创建员工主体。

router.put("/:id", (req, res) => {
  if (!ObjectId.isValid(req.params.id)) {
    return res.status(400).send(`Not a valid id ${req.params.id}`);
  }

  const { email, name, position, office, salary } = req.body;

  var emp = { email, name, position, office, salary };

  Employee.findByIdAndUpdate(
    req.params.id,
    { $set: emp },
    { new: true },
    (err, doc) => {
      if (!err) {
        if (doc) {
          res.send(doc);
        } else {
          res.status(400).send("Not found");
        }
      } else {
        console.log(err);
        res.status(500).send("Something went wrong");
      }
    }
  );
});

假设您有此员工文件。

{
    "_id" : ObjectId("5e01d6d21151ad62600b1ba6"),
    "name" : "Employee 1",
    "position" : "Web developer",
    "office" : "Software",
    "salary" : 1111,
    "email" : "emp1@microsoft.com",
    "__v" : 0
}

如果要更新职位和薪水,可以使用此request.body:

{
    "name": "Employee 1",
    "position": "Senior Web developer",
    "office": "Software",
    "salary": 2222,
    "email": "emp1@microsoft.com"
}

当您使用此正文将PUT请求发送到路线(.../5e01d6d21151ad62600b1ba6)时,结果将如下所示:

{
    "_id": "5e01d6d21151ad62600b1ba6",
    "name": "Employee 1",
    "position": "Senior Web developer",
    "office": "Software",
    "salary": 2222,
    "email": "emp1@microsoft.com",
    "__v": 0
}

答案 1 :(得分:0)

您必须使用req.body.id而不是req.params.id,因为参数仅在get方法的情况下返回。