MongoDB突变Upsert -无法在首次提交时获取新记录的ID

kr98yfug  于 2023-02-03  发布在  Go
关注(0)|答案(1)|浏览(183)

我在MongoDB上执行upsert转换来创建一个新文档或更新一个现有文档,如果文档存在,转换将返回预期的id,如果创建了一个新文档,变异返回null(在Apollo沙箱中和通过console.log),然后在后续返回中,它将返回id。我需要它立即返回新创建文档的id(在第一次返回时),以便在后续操作中使用该ID。
从一开始,这里的设置:
类型定义

updateHourByEmployeeIdByJobDate(
      jobDate: String
      startTime: String
      endTime: String
      hoursWorked: String
      employee: String
    ): Hour

分解器

updateHourByEmployeeIdByJobDate: async (
      parent,
      { jobDate, startTime, endTime, hoursWorked, employee },
      context
    ) => {
      // if (context.user) {
      console.log("resolver hours update = ");
      return Hour.findOneAndUpdate(
        { employee, jobDate },
        {
          jobDate,
          startTime,
          endTime,
          hoursWorked,
          employee,
        },
        {
          upsert: true,
        }
      );
      // }
      // throw new AuthenticationError("You need to be logged in!");
    },

突变

//UPDATE HOUR RECORD - CREATES DOCUMENT IF IT DOESN'T EXIST OR UPDATES IF IT DOES EXIST VIA THE UPSERT OPTION ON THE RESOLVER

export const UPDATE_HOURS_BYEMPLOYEEID_BYJOBDATE = gql`
  mutation UpdateHourByEmployeeIdByJobDate(
    $jobDate: String
    $startTime: String
    $endTime: String
    $hoursWorked: String
    $employee: String
  ) {
    updateHourByEmployeeIdByJobDate(
      jobDate: $jobDate
      startTime: $startTime
      endTime: $endTime
      hoursWorked: $hoursWorked
      employee: $employee
    ) {
      _id
    }
  }
`;

前端执行

const [ mostRecentHourUpdateId, setMostRecentHoursUpdateId ] = useState();

  const [updateHours] = useMutation(UPDATE_HOURS_BYEMPLOYEEID_BYJOBDATE, {
    onCompleted: (data) => {
      console.log('mutation result #1 = ', data)
      setMostRecentHoursUpdateId(data?.updateHourByEmployeeIdByJobDate?._id);
      console.log('mutation result #2 = ', mostRecentHourUpdateId)
    },
  });

  //section update database - this mutation is an upsert...it either updates or creates a record
  const handleUpdateDatabase = async (data) => {
    console.log(data);
    
    try {
      // eslint-disable-next-line
      const { data2 } = await updateHours({
        variables: {
          jobDate: moment(data.date).format("MMMM DD YYYY"), //"January 20 2023"
          startTime: `${data.startTime}:00 (MST)`, //"12:00:00 (MST)"
          endTime: `${data.endTime}:00 (MST)`, //"13:00:00 (MST)"
          hoursWorked: data.hours.toString(), //"3.0"
          employee: userId, //"6398fb54494aa98f85992da3"
        },
      });

      console.log('handle update database function = data = ', data2); //fix

    } catch (err) {
      console.error(err);
    }

    singleHoursRefetch();

  };

我试过使用onComplete作为变异请求的一部分,还试过使用useEffect,更不用说在Apollo沙箱中运行变异了。所有场景的结果都是一样的。另一种方法是重新运行useQuery以获取最近/最后创建的记录,但这似乎是一个具有挑战性的解决方案(如果在某个时候记录的排序不同)和/或看起来我应该能够立即访问新创建的记录,作为突变结果的一部分。

qmb5sa22

qmb5sa221#

您可能需要使用{ returnNewDocument: true }
就像这样:

const getData = async () => {
    const returnedRecord = await Hour.findOneAndUpdate( { employee, jobDate }, { jobDate, startTime, endTime, hoursWorked, employee, }, { upsert: true, returnNewDocument: true } );
    // do something with returnedRecord
}

getData();

如需了解更多信息:https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/

相关问题