Mongoose Unique不工作,请分配重复值

x6492ojm  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(136)

这是我的完整代码,我试图验证来自用户的数据

import { Schema, model } from 'mongoose';
import { User } from './user.interface';
const userSchema = new Schema<User>({
  id: {
    type: Number,
    required: [true, 'User ID must be unique'],
    unique: true,
  },
  username: {
    type: String,
    required: [true, 'username must be unique'],
    unique: true,
    trim:true
  },
  password: {
    type: String,
    required: [true, 'Password is required'],
  },
  email: {
    type: String,
    required: [true, 'Email is required and must be unique'],
    unique: true,
    trim: true,
    validate: [validator.isEmail, 'Invalid email format'],
  },
});
export const UserModel = model<User>('User', userSchema);

字符串
但这里的“独一无二”并不管用
另一方面,我以前的代码在下面。它的工作。

import { Schema, model } from 'mongoose';
import validator from 'validator'

const studentSchema = new Schema<Student>({
  id: {
    type: Number,
    required: [true, 'Student ID must be unique'],
    unique: true,
  },
  username: {
    type: String,
    required: [true, 'Student username must be unique'],
    unique: true,
  },
  email: {
    type: String,
    required: [true, 'Email must be unique'],
    unique: true,
    trim: true,
  },
});

export const StudentModel = model<Student>('Student', studentSchema);


我需要验证数据。一个id,用户名,和电子邮件是唯一的在我的 Mongoose

dkqlctbz

dkqlctbz1#

如果要将唯一性约束应用于现有集合,请确保没有预先存在的文档违反此唯一性约束。

db.collection.ensureIndex({ id : 1 }, { unique: true });

字符串

相关问题