You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中如何通过PUT请求为MongoDB文档新增progress数组字段

问题

我在NextJS应用里实现了Google Auth功能,逻辑如下:用户在应用中产生的进度会以数组形式存储在localStorage中;当用户完成注册后,我获取到会话信息,随后发送PUT请求到数据库,将localStorage中的数组作为新字段插入到用户文档中。

我已实现通过email查询注册用户数据的GET请求且可正常运行,现在的问题是:如何使用PUT方法插入名为progress的数组类型新字段?我不确定是否应该使用update操作。

我的MongoDB用户记录如下:

_id: 63cc85641624a77f17ca5f29
name: "John P"
email: "john.p@gmail.com"
image: "https://lh3.googleusercontent.com/a/AEdFTp7xzF4eYtyhTgRxmgP4vYdCqDa6zW…"
emailVerified: null

我想要添加的新字段为:progress: ['some data']

当前我的PUT请求代码如下:

case 'PUT':
  const updateData = await fetch(`${baseUrl}/updateOne`, {
    ...fetchOptions,
    body: JSON.stringify({
      ...fetchBody,
      filter: { email: email },
      update: {}   <---------------!!!!!
    }),
  })
  const updateDataJson = await updateData.json()
  res.status(200).json(updateDataJson.documents)
  break
解决方案

你需要用MongoDB的$set操作符来给用户文档添加新字段,这是最安全的方式——只会更新指定字段,不会覆盖整个文档。

按以下步骤修改代码:

  1. 先从localStorage取出进度数组,处理空值情况避免报错
  2. 在update对象中使用$set设置progress字段

修改后的PUT请求代码:

case 'PUT':
  // 从localStorage获取进度数据,默认空数组防止数据不存在
  const userProgress = JSON.parse(localStorage.getItem('progress')) || [];
  const updateData = await fetch(`${baseUrl}/updateOne`, {
    ...fetchOptions,
    body: JSON.stringify({
      ...fetchBody,
      filter: { email: email },
      update: {
        $set: { progress: userProgress }
      }
    }),
  })
  const updateDataJson = await updateData.json()
  res.status(200).json(updateDataJson.documents)
  break

补充说明

  • $set操作符会自动判断:如果文档中没有progress字段就添加它,已有则覆盖其值,完全匹配你的需求。
  • 如果后续需要往progress数组追加元素(而非替换整个数组),可以改用$push操作符,示例:
    update: {
      $push: { progress: 'new-progress-item' }
    }
    
    这样会把新元素追加到数组末尾,保留原有数据。

内容的提问来源于stack exchange,提问作者JohnPix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:45:34