【问题标题】:How to update array of object using node with mongodb and postman?如何使用带有 mongodb 和 postman 的节点更新对象数组?
【发布时间】:2021-03-12 10:48:48
【问题描述】:

我的对象是

{
"_id": "5fc49f48502ed001f437f49b",
"students": [
    {
        "_id": "5fc49f48502ed001f437f49c",
        "name": "John",
        "class: "5",
        "age": "9"
    },
 {
        "_id": "5fc49f48502ed001f437f49d",
        "name": "Richa",
        "class: "7",
        "age": "13"
    }
]
}

我的更新代码是:

router.put("/:id/:studetid", async (req, res) => {
try {
const student= await Student.update(
  { "students._id": req.params.studentid},
  {
    $set: {
      "students.$.name": req.body.name,
      "students.$.class": req.body.class,
      "students.$.age": req.body.age,
    },
  }
);

当我选择 id 并更新任何值表单对象时,值更新成功但其他未更新的值设置为 null..

{
"_id": "5fc49f48502ed001f437f49b",
"students": [
    {
        "_id": "5fc49f48502ed001f437f49c",
        "name": null,
        "class: "6",
        "age": null
    },
}

请谁能帮我解决这个问题...我想动态更新数据...我正在使用 Postman 发送数据

【问题讨论】:

  • 您正在使用哪个模块来更新 mangoDB,您能否添加有关您正在使用的库的更多详细信息
  • @PDHide: 题外话——但是“mangoDB”实际上是一个很棒的名字而不是 mongoDB 哈哈,现在我很想吃芒果:D
  • 让我们一起期待吧

标签: node.js mongodb express mongoose postman


【解决方案1】:

您的 url 中的变量名称不正确。

router.put("/:id/:studetid", async (req, res) => {

应该是

router.put("/:id/:studentid", async (req, res) => {

这会起作用

await Student.update(
  { "_id": req.params.studentid},
  {
    $set: {
      "name": req.body.name,
      "class": req.body.class,
      "age": req.body.age,
    },
  }
);

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多