我有一个PayloadCMS错误。ValidationError:以下字段无效:email

huangapple go评论176阅读模式
英文:

I have a PayloadCMS error. ValidationError: The following field is invalid: email

问题

我使用npx create-payload-app创建了一个负载应用程序,并选择了使用空白模板。

我有以下错误:ValidationError: 以下字段无效:电子邮件

src/seed/index.ts

import { Payload } from 'payload';
import { customerForm } from './customerForm';

export const seed = async (payload: Payload) => {
  const customerFormJSON = JSON.parse(JSON.stringify(customerForm));

  const { id: customerFormID } = await payload.create({
    collection: 'customer', 
    data: customerFormJSON,
  });

};

src/seed/customerForm.ts

export const customerForm = {
    id: '63c0651b132c8e2783f8dcae',
    updatedAt: '2023-01-12T21:25:41.113Z',
    createdAt: '2022-12-28T20:48:53.181Z',
    title: '客户表单',
    fields: [
      {
        name: 'firstName',
        label: '名字',
        width: 50,
        required: true,
        id: '63adaaba5236fe69ca8973f8',
        blockName: '名字',
        blockType: '文本',
      },
      {
        name: 'lastName',
        label: '姓氏',
        width: 50,
        required: true,
        id: '63bf4b1fd69cef4f34272f9a',
        blockName: '姓氏',
        blockType: '文本',
      },
      {
        name: 'email',
        label: '电子邮件',
        width: 100,
        required: true,
        id: '63bf4b1fd69cef4f34272f9b',
        blockName: '电子邮件',
        blockType: '文本',
      },
    ],
    redirect: {},
  };

src/collections/Customers.ts

import { CollectionConfig, Block } from 'payload/types';

export const Customers: CollectionConfig = {
  slug: 'customer',
  // auth: true,
  fields: [
    {
      name: 'firstName',
      type: '文本',
      // required: true,
    },
    {
      name: 'lastName',
      type: '文本',
      // required: true,
    },
    {
      name: 'email',
      type: '文本',
      // required: true,
    },
  ]
}

src/server.ts

import express from 'express';
import payload from 'payload';
import { seed } from './seed';


require('dotenv').config();
const app = express();

// 重定向根目录到管理员面板
app.get('/', (_, res) => {
  res.redirect('/admin');
});

const start = async () => {
  // 初始化 Payload
  await payload.init({
    secret: process.env.PAYLOAD_SECRET,
    mongoURL: process.env.MONGODB_URI,
    express: app,
    email: {
      fromName: '管理员',
      fromAddress: 'admin@example.com',
      logMockCredentials: true,
    },
    onInit: async () => {
      payload.logger.info(`Payload 管理员 URL: ${payload.getAdminURL()}`)
    },
  })

  // 在此添加您自己的 express 路由

  if (process.env.PAYLOAD_SEED === 'true') {
    payload.logger.info('---- 正在填充数据库 ----');
    await seed(payload);
  }

  app.listen(3000);
}

start();

当我在customers.ts中取消注释(required: true)时,我得到以下错误:ValidationError: 以下字段无效:名字,姓氏

当我在customers.ts中注释掉(required: true)时,我得到以下错误:ValidationError: 以下字段无效:电子邮件

注意:我只想使用payload.create来创建数据。任何帮助将不胜感激。

英文:

I create a payload app using
npx create-payload-app
and I chose to use blank template

I have this. ValidationError: The following field is invalid: email

src/seed/index.ts

import { Payload } from 'payload';
import { customerForm } from './customerForm';

export const seed = async (payload: Payload) => {
  const customerFormJSON = JSON.parse(JSON.stringify(customerForm));

  const { id: customerFormID } = await payload.create({
    collection: 'customer', 
    data: customerFormJSON,
  });

};

src/seed/customerForm.ts

export const customerForm = {
    id: '63c0651b132c8e2783f8dcae',
    updatedAt: '2023-01-12T21:25:41.113Z',
    createdAt: '2022-12-28T20:48:53.181Z',
    title: 'Customer Form',
    fields: [
      {
        name: 'firstName',
        label: 'First name',
        width: 50,
        required: true,
        id: '63adaaba5236fe69ca8973f8',
        blockName: 'first-name',
        blockType: 'text',
      },
      {
        name: 'lastName',
        label: 'Last name',
        width: 50,
        required: true,
        id: '63bf4b1fd69cef4f34272f9a',
        blockName: 'last-name',
        blockType: 'text',
      },
      {
        name: 'email',
        label: 'Email',
        width: 100,
        required: true,
        id: '63bf4b1fd69cef4f34272f9b',
        blockName: 'email',
        blockType: 'text',
      },
    ],
    redirect: {},
  };
  

src/collections/Customers.ts

import { CollectionConfig, Block } from 'payload/types';

export const Customers: CollectionConfig = {
  slug: 'customer',
  // auth: true,
  fields: [
    {
      name: 'firstName',
      type: 'text',
      // required: true,
    },
    {
      name: 'lastName',
      type: 'text',
      // required: true,
    },
    {
      name: 'email',
      type: 'text',
      // required: true,
    },
  ]
}

src/server.ts

import express from 'express';
import payload from 'payload';
import { seed } from './seed'


require('dotenv').config();
const app = express();

// Redirect root to Admin panel
app.get('/', (_, res) => {
  res.redirect('/admin');
});

const start = async () => {
  // Initialize Payload
  await payload.init({
    secret: process.env.PAYLOAD_SECRET,
    mongoURL: process.env.MONGODB_URI,
    express: app,
    email: {
      fromName: 'Admin',
      fromAddress: 'admin@example.com',
      logMockCredentials: true,
    },
    onInit: async () => {
      payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`)
    },
  })

  // Add your own express routes here

  if (process.env.PAYLOAD_SEED === 'true') {
    payload.logger.info('---- SEEDING DATABASE ----');
    await seed(payload);
  }

  app.listen(3000);
}

start();

When I uncomment (required: true) in customers.ts
I get this error: ValidationError: followingFieldsInvalid firstName, lastName

when I comment (required: true) in customers.ts
ValidationError: The following field is invalid: email

NB: I only want to use payload.create for creating data.

Any help is appreciated

答案1

得分: 3

我找到了问题。
问题是我删除/注释了字段email、firstName或lastName上的唯一约束,但忘记更新数据库。
即使我从Payload CMS集合配置中删除了email、firstName、lastName或name的唯一约束,如果在我的更改后未正确更新,MongoDB可能仍会在数据库级别执行它。我手动检查了我的MongoDB集合的索引,以确认'name'字段上的唯一约束是否仍然存在。

像这样:

mydb> db.generics.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { name: 1 },
name: 'name_1',
background: true,
unique: true
}
]
mydb> db.generics.dropIndex("name_1")
{ nIndexesWas: 2, ok: 1 }
英文:

I figured the issue.
The issue was that I deleted/commented the unique constraint on the on the fields email, firstName or lastName but forgot to update the database.
Even though I removed the unique constraint from your Payload CMS collection configuration (for email, firstName, lastName, or name) , MongoDB might still enforce it at the database level if it wasn't properly updated after my changes. I manually inspected my MongoDB collection's indexes to confirm whether the unique constraint on the 'name' field still exists.

like this:

mydb> db.generics.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { name: 1 },
name: 'name_1',
background: true,
unique: true
}
]
mydb> db.generics.dropIndex("name_1")
{ nIndexesWas: 2, ok: 1 }

huangapple
  • 本文由 发表于 2023年6月16日 03:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484774.html
  • content-management-system
  • javascript
  • node.js
  • payload-cms
  • typescript
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定