Mongoose findOneAndUpdate() 执行多次

问题描述 投票:0回答:1

一些背景知识,我有一个使用 MongoDB 作为数据库的应用程序的快速后端。 Auth0 作为身份提供者存在。

我有一个

addTeamUser
异步函数:

  1. 使用 Joi 验证请求正文
  2. 从请求正文中获取电子邮件
  3. 在 Auth0 数据库中创建一个用户
  4. 成功后,使用 auth0 id 和 email 构造一个用户对象
  5. 使用 mongoose 的
    findOneAndUpdate
  6. 将该用户推送到我本地数据库中的一组用户中

代码如下图:

const addTeamUser = async (req) => {
  // Get team_id from JWT token
  const team_id = req.auth.team_id;
  const data = req.body;
  // Joi validation for the email body
  const { error } = schema.user.validate(data, { abortEarly: false });

  if (error) {
    return { message: error.message, statusCode: 400 };
  }

  try {
    // Call auth0 management API and create new user with the email provided and custom team_id in app_metadata
    const createdUser = await managementAPI.createUser({
      email: data.email,
      connection: 'Username-Password-Authentication',
      password: "changeme",
      app_metadata: {
        team_id: team_id,
      },
    });

    // Add user to local database if Management API returned a success
    const user = {
      id: createdUser.user_id,
      email: createdUser.email
    };

    const doc = await Team.findOneAndUpdate(
      { team_id },
      { $push: { users: user } },
      { new: true });

    return {
      statusCode: 201,
      users: doc.users,
      message: "User added successfully"
    }

  } catch (err) {
    console.error('Error creating user:', err);
    return { message: 'An error occurred, try again later', statusCode: 500 };
  }
};

现在这就像一个魅力......除了当用户被插入本地数据库时,它有时会插入两次并且我最终在我的数组中有两个相同的用户。

我读了一些书,显然我不能同时使用 await 和回调,但无论我做什么来修复它,它都会执行两次。

这是我的团队架构以获得更多背景信息:

const teamSchema = new Schema({
  team_id: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true,
    trim: true,
  },
  users: [
    {
      id: {
        type: String,
        unique: true,
        required: true,
        trim: true
      },
      email: {
        type: String,
        unique: true,
        required: true,
        trim: true
      }
    }
  ],
}, {
  _id: false // This disables the automatic _id field for subdocuments
});

请告诉我这个错误是怎么回事,我该如何解决?

node.js mongodb mongoose auth0 findoneandupdate
1个回答
0
投票

findOneAndUpdate
方法将用户插入两次的原因是因为
{new:true}
标志。所以删除它会解决你的问题。有关更多信息,请查看上一个问题:

使用 Mongoose 创建方法时,文档被两次插入 MongoDB

© www.soinside.com 2019 - 2024. All rights reserved.