# 我是如何把 18.2 万用户迁移到 Supabase 的

By Tarik Pinarci (https://tarikpinarci.com). Published 2025-03-30. Canonical: https://tarikpinarci.com/zh/blog/migration-to-supabase

从拖了好几个月，到最终迁移完 18.2 万用户：我是怎么把应用搬到 Supabase 上的。

把 182,000 名用户迁移到一个新的后端可不是小事，尤其当你是一个还要兼顾全职工作的独立移动开发者时。但我做到了。我把我的应用 OSM Tactics 从一团乱麻的 NestJS + MongoDB 架构，迁移到了 Supabase，也就是现在后端圈子里的热门话题。在这篇文章里，我会带你走一遍整个过程：我为什么选择 Supabase，遇到了哪些挑战，以及我是如何完成迁移的。

### 为什么选 Supabase？

当我觉得应用的后端越来越老旧时，我开始寻找更好的方案，Supabase 引起了我的注意。它是一个开源项目，有点像 Firebase，但上手更简单。它给你一个带有易用 API 的 PostgreSQL 数据库，还配好了实时功能和登录功能。对我这样一个做移动应用的人来说，这再合适不过了，因为我不想折腾复杂的服务器杂事。大概五分钟就能跑起一个 Supabase 项目，文档也非常直白，所以即使我不是后端高手，也没有觉得无从下手。

不过 Supabase 不只是简单，它还在快速壮大。它现在还没有 Firebase 那么庞大，但已经有大量开发者在用，社区增长得很快。我需要的它都有：存数据的数据库、登录工具、上传文件的地方，甚至还有不需要完整服务器就能运行的小函数。Firebase 把内部工作原理藏了起来，而 Supabase 用的是 PostgreSQL，一个老牌、可靠、被很多人信任的数据库。这意味着我可以按自己的想法修改，以后也能扩展规模而不会被卡住。另外，网上有一大群开发者在 GitHub 等地方分享技巧、窍门和修复方法。我知道如果卡住了，可以 Google 一下或者找人问问。对我这样时间紧张的独立开发者来说，Supabase 感觉是正确的选择：它够简单，又足够强大，撑得起我的应用。

### 大迁移之前的旧架构

![](https://cdn-images-1.medium.com/max/2000/0*8Dz9gnNI7LqoicSk.gif)

在讲迁移到 Supabase 之前，先说说我之前用的是什么。我的应用 [OSM Tactics](https://apps.apple.com/us/app/osm-tactics/id1632773385) 是一款 Android 和 iOS 上的手游，玩家可以在里面规划战术策略，如果你喜欢这类东西，它挺酷的。后端是我自己用 NestJS 搭的，NestJS 是一个 Node.js 框架，我喜欢它是因为它支持 TypeScript，而且能让代码保持条理。它连接的是 MongoDB，我把所有用户信息、游戏数据和其他零碎数据都存在里面。这套架构我已经跑了将近四年。

![迁移前 MongoDB 的最后一张快照，Osm Tactics 又名“Osm Guide”](https://cdn-images-1.medium.com/max/4072/1*oPXY2-yvVmlns_ufWV4ZGg.png)_迁移前 MongoDB 的最后一张快照，Osm Tactics 又名“Osm Guide”_

但问题在于：我只是一个有全职工作的人，维持这个后端运转快把我累垮了。一开始，NestJS 和 MongoDB 还应付得过来。但随着用户越来越多，情况变得一团糟。我得花太多时间确保服务器不崩、修补安全漏洞、保证速度够快。安全是最糟的部分：我懂一些 Node.js，但我是做移动应用的，不是后端专家。它勉强还能用，但就像一辆老是抛锚的旧车。我不能永远这样修修补补，我需要一个不会让我抓狂的新方案。

### 迈出那一步：决定迁移

![](https://cdn-images-1.medium.com/max/2000/1*CUFLlvoA2ItnVtEFWJulrg.png)

决定把所有东西搬走并不是一时冲动，因为我一直拖着，这个决定花了很长时间。OSM Tactics 并不是什么功能繁多的巨型应用，但 18.2 万用户的数据量可不小。从数据结构松散自由的 MongoDB，迁移到所有东西都整整齐齐放在表里的 Supabase PostgreSQL，听起来就很难。我得重新设计数据结构，还要确保不丢失任何重要的东西。旧的 NestJS 加 MongoDB 组合还在运行，但我有种不好的预感，觉得它很快就会出大问题。这种担忧一直困扰着我，直到我终于说：“好吧，动手吧。”

下定决心之后，我必须好好做规划。我坐下来琢磨怎么把 MongoDB 里的数据变成 Supabase 的表，就像画一张地图，标出每样东西该放在哪里。第一步是把所有数据安全地从 MongoDB 导出来，所以我写了一个小脚本，把数据导出成 JSON 文件。代码如下，很基础，但能完成任务：

```javascript
async function exportCollection(collectionName, outputFileName, query = {}) {
  try {
    await mongoose.connect(mongoURI);

    const Model = mongoose.model(
      collectionName,
      genericSchema,
      collectionName.toLowerCase()
    );

    const documents = await Model.find(query).lean();

    const outputPath = path.join(__dirname, outputFileName);
    fs.writeFileSync(outputPath, JSON.stringify(documents, null, 2));

    await mongoose.disconnect();

    return documents;
  } catch (error) {
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
    }
  }
}
```

这个脚本连接到 MongoDB，取出所有数据，再以 JSON 文件的形式保存到我的电脑上。它就像一份备份：就算我搞砸了，也能随便折腾而不至于丢掉一切。我对每个 collection 都跑了一遍，检查文件确认内容没问题，知道手里有副本之后心里踏实了一些。不过，真正开工之前我还是磨蹭了很久：盯着屏幕，喝口咖啡，心想“要不明天再说”。我花了很大力气才不再偷懒、真正投入进去，但一旦开始，我就全力以赴了。

### 迁移用户：密码难题

真正棘手的地方来了：迁移 18.2 万用户，同时保证他们的密码依然可用。用户希望在我更新应用之后，还能用同样的邮箱和密码登录，这本来就是理所应当的。但真正做起来简直是一场噩梦。好在 [Supabase 用 bcrypt 存储密码](https://supabase.com/docs/guides/auth/password-security#how-are-passwords-stored)，和 MongoDB 里的一样，所以我不用全部重新处理，也不用让用户设置新密码。否则体验会非常糟糕：大家都讨厌重置密码，我会因此流失一大批用户。

### 应对 Supabase 挑剔的 Auth 表

Supabase 用 auth.users 表来处理登录，它非常严格。表里有一大堆字段，你必须填得恰到好处，否则它就会出问题，比如你填了空字符串而不是 null，它就会报错。我在[这个 GitHub 讨论](https://github.com/supabase/auth/issues/1940)里看到了其他人遇到的错误，看完我就老实了。我必须完全对上它的格式。下面是 Supabase 中一个用户的样子（我没用手机号相关的功能，所以那些字段是 null，如果你用到了请自行修改）：

```javascript
const supabaseUser = {
  id: uid,
  email: user.email,
  encrypted_password: user.password || null,
  instance_id: "00000000–0000–0000–0000–000000000000",
  aud: "authenticated",
  role: "authenticated",
  email_confirmed_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  created_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  updated_at: user.updatedAt ? new Date(user.updatedAt).toISOString() : null,
  last_sign_in_at: null,
  phone: user.phone || null,
  phone_confirmed_at: null,
  confirmed_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  invited_at: null,
  confirmation_token: "",
  confirmation_sent_at: null,
  recovery_token: "",
  recovery_sent_at: null,
  email_change_token_new: "",
  email_change: "",
  email_change_sent_at: null,
  email_change_token_current: "",
  email_change_confirm_status: 0,
  banned_until: null,
  reauthentication_token: "",
  reauthentication_sent_at: null,
  is_super_admin: null,
  phone_change: "",
  phone_change_token: "",
  phone_change_sent_at: null,
  is_sso_user: false,
  deleted_at: null,
  is_anonymous: false,
  raw_user_meta_data: JSON.stringify(rawUserMetaData),
  raw_app_meta_data: JSON.stringify(rawAppMetaData),
};
```

每一个字段我都必须填对，否则 Supabase 不会接受。为了迁移 MongoDB 里的所有用户，我写了一个更大的脚本，把用户取出来，转换成这种格式，再保存为 CSV 文件。脚本如下，有点长，但展示了完整的过程：

```javascript
const fs = require("fs");
const path = require("path");
const { parse } = require("json2csv");
const { v4: uuidv4 } = require("uuid");
const mongoose = require("mongoose");
const mongoURI = "your-connection-string";

// Define a generic schema for flexible document structure
const userSchema = new mongoose.Schema({}, { strict: false });
async function fetchUsersFromMongoDB() {
  try {
    console.log("Connecting to MongoDB…");
    await mongoose.connect(mongoURI);
    console.log("Connected to MongoDB");
    const UserModel = mongoose.model("Users", userSchema, "users");
    console.log("Fetching users from MongoDB…");
    const users = await UserModel.find({}).lean();
    console.log(`Found ${users.length} users in MongoDB`);
    await mongoose.disconnect();
    console.log("Disconnected from MongoDB");
    return users;
  } catch (error) {
    console.error("Error fetching users from MongoDB:", error);
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
    }
    throw error;
  }
}

async function processUsers() {
  console.time("Total processing time");
  const mongoUsersFilePath = path.join(__dirname, "mongo_users.json");
  try {
    // Step 1: Fetch users from MongoDB
    const users = await fetchUsersFromMongoDB();
    // Step 2: Write users to a fresh JSON file
    fs.writeFileSync(mongoUsersFilePath, JSON.stringify(users, null, 2));
    console.log(`Fresh users data written to: ${mongoUsersFilePath}`);
    // Step 3: Read the fresh users file
    const usersData = JSON.parse(fs.readFileSync(mongoUsersFilePath, "utf8"));
    console.log(`Read ${usersData.length} users from fresh file`);
    // Step 4: Filter users to include only those with an email or at least one provider
    const filteredUsers = usersData.filter((user) => {
      return user.email || user.googleId || user.appleId;
    });
    console.log(`Filtered users: ${filteredUsers.length}`);
    // Create a Set to track used IDs and ensure uniqueness
    const usedIds = new Set();
    const usedEmails = new Set();
    const duplicateEmails = [];
    // Step 5: Transform the data to match Supabase Auth users structure
    const transformedUsers = [];
    filteredUsers.forEach((user) => {
      if (!user.email) {
        console.log("Skipping user without email:", user._id);
        return;
      }
      // Check for duplicate email
      const lowerEmail = user.email.toLowerCase();
      if (usedEmails.has(lowerEmail)) {
        duplicateEmails.push({
          email: user.email,
          id: user._id,
          googleId: user.googleId,
          appleId: user.appleId,
        });
        console.warn(`Duplicate email detected and skipped: ${user.email}`);
        return;
      }
      // Mark this email as used
      usedEmails.add(lowerEmail);
      let uid = uuidv4();
      while (usedIds.has(uid)) {
        console.warn("Duplicate ID detected:", uid);
        uid = uuidv4();
      }
      usedIds.add(uid);
      const rawUserMetaData = {
        sub: uid,
        email: user.email,
        email_verified: true,
        phone_verified: false,
      };
      const providers = [];
      // Check for Google ID
      if (user.googleId) {
        providers.push("google");
        rawUserMetaData.iss = "https://accounts.google.com";
        rawUserMetaData.sub = user.googleId;
        rawUserMetaData.provider_id = user.googleId;
      }
      // Check for Apple ID
      if (user.appleId) {
        providers.push("apple"); // Only override iss and sub if Google wasn't already set
        if (!user.googleId) {
          rawUserMetaData.iss = "https://appleid.apple.com";
          rawUserMetaData.sub = user.appleId;
          rawUserMetaData.provider_id = user.appleId;
        }
      }
      // If no external providers, use email
      if (providers.length === 0) {
        providers.push("email");
      }
      // Set the raw app metadata
      const rawAppMetaData = {
        provider: providers[0], // Primary provider is the first one
        providers: providers, // All providers in an array
      };
      transformedUsers.push({
        id: uid,
        email: user.email || null,
        encrypted_password: user.password,
        instance_id: "00000000–0000–0000–0000–000000000000",
        aud: "authenticated",
        role: "authenticated",
        invited_at: null,
        confirmation_token: "",
        confirmation_sent_at: null,
        recovery_token: "",
        recovery_sent_at: null,
        email_change_token_new: "",
        email_change: "",
        email_change_sent_at: null,
        last_sign_in_at: new Date().toISOString(),
        is_super_admin: null,
        phone: "",
        phone_confirmed_at: null,
        phone_change: "",
        phone_change_token: "",
        phone_change_sent_at: null,
        confirmed_at: new Date().toISOString(),
        email_change_token_current: "",
        email_change_confirm_status: 0,
        banned_until: null,
        reauthentication_token: "",
        reauthentication_sent_at: null,
        is_sso_user: false,
        deleted_at: null,
        is_anonymous: false,
        created_at: user.createdAt
          ? new Date(user.createdAt).toISOString()
          : new Date().toISOString(),
        updated_at: null,
        email_confirmed_at: user.createdAt
          ? new Date(user.createdAt).toISOString()
          : new Date().toISOString(),
        phone: user.phone || null,
        phone_confirmed_at: null,
        raw_user_meta_data: rawUserMetaData,
        raw_app_meta_data: rawAppMetaData,
      });
    });
    // Step 6: Convert the transformed data to CSV
    const csvFields = [
      "id",
      "email",
      "encrypted_password",
      "instance_id",
      "aud",
      "role",
      "email_confirmed_at",
      "invited_at",
      "confirmation_token",
      "confirmation_sent_at",
      "recovery_token",
      "recovery_sent_at",
      "email_change_token_new",
      "email_change",
      "email_change_sent_at",
      "last_sign_in_at",
      "raw_app_meta_data",
      "raw_user_meta_data",
      "is_super_admin",
      "created_at",
      "updated_at",
      "phone",
      "phone_confirmed_at",
      "phone_change",
      "phone_change_token",
      "phone_change_sent_at",
      "confirmed_at",
      "email_change_token_current",
      "email_change_confirm_status",
      "banned_until",
      "reauthentication_token",
      "reauthentication_sent_at",
      "is_sso_user",
      "deleted_at",
      "is_anonymous",
    ];
    // Write duplicate emails to a file for reference
    if (duplicateEmails.length > 0) {
      fs.writeFileSync(
        path.join(__dirname, "duplicate_emails.json"),
        JSON.stringify(duplicateEmails, null, 2)
      );
      console.log("Duplicate emails written to duplicate_emails.json");
    }
    const csv = parse(transformedUsers, { fields: csvFields });
    // Step 7: Write the CSV to a file
    const csvFilePath = path.join(__dirname, "supabase_users.csv");
    fs.writeFileSync(csvFilePath, csv);
    console.log("CSV file has been generated:", csvFilePath);
    // Step 8: Delete the temporary fresh users file
    if (fs.existsSync(mongoUsersFilePath)) {
      fs.unlinkSync(mongoUsersFilePath);
      console.log(`Temporary file deleted: ${mongoUsersFilePath}`);
    }
    console.timeEnd("Total processing time");
  } catch (error) {
    console.error("Error processing users:", error);
  } finally {
    if (fs.existsSync(mongoUsersFilePath)) {
      try {
        fs.unlinkSync(mongoUsersFilePath);
        console.log(`Temporary file deleted: ${mongoUsersFilePath}`);
      } catch (deleteError) {
        console.error(`Error deleting temporary file: ${deleteError.message}`);
      }
    }
  }
}
```

拿到这个 CSV 之后，我在 Supabase 里建了一张和 auth.users 结构一样的临时表。真实表的定义是一长段 SQL，你可以在 Supabase 编辑器的 schema auth > users > Definition 下看到：

```sql
    create table auth.users (
      instance_id uuid null,
      id uuid not null,
      aud character varying(255) null,
      role character varying(255) null,
      email character varying(255) null,
      encrypted_password character varying(255) null,
      email_confirmed_at timestamp with time zone null,
      invited_at timestamp with time zone null,
      confirmation_token character varying(255) null,
      confirmation_sent_at timestamp with time zone null,
      recovery_token character varying(255) null,
      recovery_sent_at timestamp with time zone null,
      email_change_token_new character varying(255) null,
      email_change character varying(255) null,
      email_change_sent_at timestamp with time zone null,
      last_sign_in_at timestamp with time zone null,
      raw_app_meta_data jsonb null,
      raw_user_meta_data jsonb null,
      is_super_admin boolean null,
      created_at timestamp with time zone null,
      updated_at timestamp with time zone null,
      phone text null default null::character varying,
      phone_confirmed_at timestamp with time zone null,
      phone_change text null default ''::character varying,
      phone_change_token character varying(255) null default ''::character varying,
      phone_change_sent_at timestamp with time zone null,
      confirmed_at timestamp with time zone GENERATED ALWAYS as (LEAST(email_confirmed_at, phone_confirmed_at)) STORED null,
      email_change_token_current character varying(255) null default ''::character varying,
      email_change_confirm_status smallint null default 0,
      banned_until timestamp with time zone null,
      reauthentication_token character varying(255) null default ''::character varying,
      reauthentication_sent_at timestamp with time zone null,
      is_sso_user boolean not null default false,
      deleted_at timestamp with time zone null,
      is_anonymous boolean not null default false,
      constraint users_pkey primary key (id),
      constraint unique_email unique (email),
      constraint users_phone_key unique (phone),
      constraint users_email_change_confirm_status_check check (
        (
          (email_change_confirm_status >= 0)
          and (email_change_confirm_status <= 2)
        )
      )
    ) TABLESPACE pg_default;

    create unique INDEX IF not exists confirmation_token_idx on auth.users using btree (confirmation_token) TABLESPACE pg_default
    where
      ((confirmation_token)::text !~ '^[0-9 ]*$'::text);

    create unique INDEX IF not exists email_change_token_current_idx on auth.users using btree (email_change_token_current) TABLESPACE pg_default
    where
      (
        (email_change_token_current)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists email_change_token_new_idx on auth.users using btree (email_change_token_new) TABLESPACE pg_default
    where
      (
        (email_change_token_new)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists reauthentication_token_idx on auth.users using btree (reauthentication_token) TABLESPACE pg_default
    where
      (
        (reauthentication_token)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists recovery_token_idx on auth.users using btree (recovery_token) TABLESPACE pg_default
    where
      ((recovery_token)::text !~ '^[0-9 ]*$'::text);

    create unique INDEX IF not exists users_email_partial_key on auth.users using btree (email) TABLESPACE pg_default
    where
      (is_sso_user = false);

    create index IF not exists users_instance_id_email_idx on auth.users using btree (instance_id, lower((email)::text)) TABLESPACE pg_default;

    create index IF not exists users_instance_id_idx on auth.users using btree (instance_id) TABLESPACE pg_default;

    create index IF not exists users_is_anonymous_idx on auth.users using btree (is_anonymous) TABLESPACE pg_default;
```

我照着这个定义建了临时表，把 CSV 上传进去，然后用下面这个脚本，每次一千条，把用户迁移到真正的 auth.users 表里：

```sql
    DO $$
    DECLARE
        batch_size INT := 1000;  -- Adjust batch size as needed
        records_inserted INT;
    BEGIN
        LOOP
            INSERT INTO auth.users (
                id,
                email,
                encrypted_password,
                instance_id,
                aud,
                role,
                email_confirmed_at,
                invited_at,
                confirmation_token,
                confirmation_sent_at,
                recovery_token,
                recovery_sent_at,
                email_change_token_new,
                email_change,
                email_change_sent_at,
                last_sign_in_at,
                raw_app_meta_data,
                raw_user_meta_data,
                is_super_admin,
                created_at,
                updated_at,
                phone,
                phone_confirmed_at,
                phone_change,
                phone_change_token,
                phone_change_sent_at,
                email_change_token_current,
                email_change_confirm_status,
                banned_until,
                reauthentication_token,
                reauthentication_sent_at,
                is_sso_user,
                deleted_at,
                is_anonymous
            )
            SELECT
                id,
                email,
                encrypted_password,
                COALESCE(instance_id, '00000000-0000-0000-0000-000000000000'),
                COALESCE(aud, 'authenticated'),
                COALESCE(NULLIF(role, ''), 'authenticated'),
                COALESCE(email_confirmed_at, NOW()),
                COALESCE(invited_at, NULL),
                COALESCE(confirmation_token, ''),
                COALESCE(confirmation_sent_at, NULL),
                COALESCE(recovery_token, ''),
                COALESCE(recovery_sent_at, NULL),
                COALESCE(email_change_token_new, ''),
                COALESCE(email_change, ''),
                COALESCE(email_change_sent_at, NULL),
                COALESCE(last_sign_in_at, NOW()),
                raw_app_meta_data,  -- Use value from test_users table
                raw_user_meta_data, -- Use value from test_users table
                COALESCE(is_super_admin, NULL),
                COALESCE(created_at, NOW()),
                COALESCE(updated_at, NOW()),
                COALESCE(phone, NULL),
                COALESCE(phone_confirmed_at, NULL),
                COALESCE(phone_change, ''),
                COALESCE(phone_change_token, ''),
                COALESCE(phone_change_sent_at, NULL),
                COALESCE(email_change_token_current, ''),
                COALESCE(email_change_confirm_status, 0),
                COALESCE(banned_until, NULL),
                COALESCE(reauthentication_token, ''),
                COALESCE(reauthentication_sent_at, NULL),
                COALESCE(is_sso_user, false),
                COALESCE(deleted_at, NULL),
                COALESCE(is_anonymous, false)
            FROM public.test_users
            LIMIT batch_size
            ON CONFLICT (email) DO NOTHING;  -- Ignore duplicates

            GET DIAGNOSTICS records_inserted = ROW_COUNT;

            -- Exit the loop if no more records are inserted
            IF records_inserted = 0 THEN
                EXIT;
            END IF;
        END LOOP;
    END $$;
```

这样我能看清每一步：导出、转换、加载。这可能比用某个高级工具花的时间更长，但我喜欢清楚地知道到底发生了什么。加载完 CSV 后，我会检查临时表，抽查几行数据，然后盯着批处理脚本运行，确保它不会卡住。

### 没有自定义字段的空间

Supabase 的 auth.users 表不允许你添加自己的字段，这让我有点措手不及。在 MongoDB 里，我直接往里面塞一个 username 字段就行，没什么大不了的。但 Supabase 不允许，你只能用它提供的字段。我考虑过把额外的数据塞进 raw_user_meta_data，它就像一个 JSON 袋子，但这样以后搜索起来会很乱。所以我另外建了一张 profiles 表，通过用户 ID 和 auth.users 关联，用来存 username 和 locale 之类的数据，让一切保持整洁。

另外也可以看看这个讨论，可能会有帮助：[https://github.com/orgs/supabase/discussions/3491](https://github.com/orgs/supabase/discussions/3491)

这样设置意味着更多工作：我得从 MongoDB 里取出这些额外字段，把它们对应到正确的用户，再加载进新表。我又写了一个脚本来抓取这些数据，转换成 CSV，在 auth 部分完成后上传到 Supabase。现在的结构更好了，因为以后我可以添加更多字段而不会破坏任何东西，但由于要处理两张表而不是一张，迁移花的时间也更长了。

### 迁移 Google/Apple 登录

![](https://cdn-images-1.medium.com/max/2400/0*ojwVN2SEuLBx9Ybn.jpeg)

Google 和 Apple 登录也很让人头疼。在 MongoDB 里，我有 googleId 和 appleId 字段，有些用户的同一个邮箱同时绑定了两者。Supabase 则通过 raw_user_meta_data 中的 iss、sub 和 provider_id 等特殊字段来处理它们。

我是这样设置的：

```javascript
const uid = uuidv4();
const providers = [];
// Build raw user metadata
const rawUserMetaData = {
  sub: uid,
  email: user.email,
  email_verified: true,
  phone_verified: false,
};
// Check for Google ID
if (user.googleId) {
  providers.push("google");
  rawUserMetaData.iss = "https://accounts.google.com";
  rawUserMetaData.sub = user.googleId;
  rawUserMetaData.provider_id = user.googleId;
}
// Check for Apple ID
if (user.appleId) {
  providers.push("apple");
  if (!user.googleId) {
    rawUserMetaData.iss = "https://appleid.apple.com";
    rawUserMetaData.sub = user.appleId;
    rawUserMetaData.provider_id = user.appleId;
  }
}
// If no external providers, use email
if (providers.length === 0) {
  providers.push("email");
}
```

在应用里，我把登录流程改成了使用 Supabase 的 API。Apple 登录：

```javascript
import * as AppleAuthentication from "expo-apple-authentication";
import { supabase } from "your-supabase-client";

const credential = await AppleAuthentication.signInAsync({
  requestedScopes: [
    AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
    AppleAuthentication.AppleAuthenticationScope.EMAIL,
  ],
});
if (credential.identityToken) {
  const { data, error } = await supabase.auth.signInWithIdToken({
    provider: "apple",
    token: credential.identityToken,
  });
}
```

Google 登录：

```javascript
import { GoogleSignin } from "@react-native-google-signin/google-signin";
import { supabase } from "your-supabase-client";

const googleUser = await GoogleSignin.signIn();

if (googleUser.idToken) {
  const { data, error } = await supabase.auth.signInWithIdToken({
    provider: "google",
    token: googleUser.idToken,
  });
}
```

这样是可行的，但处理同时绑定了 Google 和 Apple 的用户比较棘手：我必须选一个作为主 ID，另一个作为附加项。我在应用里反复测试，确保没有人被锁在门外。

> **注意：Supabase 中导出 CSV 可能存在的问题**
> 截至今天（2025 年 3 月 29 日），把表数据导出为 CSV 可能[不太可靠](https://github.com/supabase/supabase/issues/27102)，在对比 Supabase 和原始数据源的数据时请记住这一点。

### 生成 TypeScript 类型

Supabase 有个很棒的功能，可以帮你生成 TypeScript 类型。[只要运行一条命令](https://supabase.com/docs/guides/api/rest/generating-types#generating-types-using-supabase-cli)，它就会生成文件，准确告诉你的代码数据库长什么样。对我的 React Native 和 Expo 应用来说，这太有用了：我不用再猜会拿到什么数据，也不用自己写类型。它大大减少了 bug，因为一旦写错，TypeScript 就会报错提醒我。以前我要花好几个小时修一些低级错误，现在快多了。

建好表之后，我运行了这条命令，拿到类型文件，接入了应用。一下子，像 user.email 或 profile.username 这样的写法就直接可用了，不用再担心有没有拼错。这是件小事，但它让写应用不再像猜谜游戏，而更像是稳操胜券。

### 让数据库函数来干活

Supabase 允许你编写在数据库中运行的小型 SQL 函数，非常方便。我不用在应用端写一堆代码去修改数据，而是交给数据库处理。

下面是我写的一个给用户 profile 增加积分的函数：

```sql
    declare
      current_credits int;
      new_credits int;
    begin
      -- Get current credits from user_profiles table
      select assistant_credits
      into current_credits
      from public.user_profiles
      where public.user_profiles.user_id = increase_assistant_credits.user_id;

      if current_credits is null then
        current_credits := 0;
      end if;

      new_credits := current_credits + credits_to_add;

      -- Update assistant_credits in user_profiles table
      update public.user_profiles
      set assistant_credits = new_credits
      where public.user_profiles.user_id = increase_assistant_credits.user_id;

      return new_credits;
    end;
```

它读取用户的积分，加上一些，再保存回去，一步到位。如果没有它，我就得先取出积分，在应用里相加，再写回去，这意味着更多代码和更多出错的机会。我还为其他任务写了几个类似的函数，由于繁重的工作交给了数据库，应用感觉也更灵敏了。

### 关于后端的一点说明

这里有个转折：Supabase 并没有让我彻底摆脱后端。要使用一些管理员级别的认证功能，你需要 [service_role key](https://supabase.com/docs/guides/api/api-keys#the-servicerole-key)，但不能把它放进应用里，那样不安全。所以我保留了一个小型的 NestJS 服务器来处理这些机密任务。它没有以前那么大，但它的存在是为了保证安全。大部分工作由 Supabase 完成，所以还是比我以前的架构轻松得多。

### 总结：这番折腾是值得的

![](https://cdn-images-1.medium.com/max/2000/0*rugop3f6Ns9U4Ayl.jpg)

把 182,000 名用户迁移到 Supabase，不仅是技术上的挑战，也是心理上的挑战。拖延、熬夜，再加上无数次的自我怀疑，有些时候我真的以为自己会把一切都搞砸。这是一个缓慢而艰苦的过程，充满了压力和犹豫。但告别脆弱的 NestJS + MongoDB 架构，换成更简洁、更易维护的方案，绝对是值得的。

作为一个还要兼顾全职工作的独立开发者，Supabase 给了我所需要的简单、灵活和社区支持。如果你也在考虑迁移自己应用的后端，要知道这完全是可以做到的。它不会很快，也不会毫无痛苦，但只要做一些规划（可能还要熬几个长夜），你最终会得到一套真正值得信赖的架构。

