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

x6492ojm  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(143)

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

  1. import { Schema, model } from 'mongoose';
  2. import { User } from './user.interface';
  3. const userSchema = new Schema<User>({
  4. id: {
  5. type: Number,
  6. required: [true, 'User ID must be unique'],
  7. unique: true,
  8. },
  9. username: {
  10. type: String,
  11. required: [true, 'username must be unique'],
  12. unique: true,
  13. trim:true
  14. },
  15. password: {
  16. type: String,
  17. required: [true, 'Password is required'],
  18. },
  19. email: {
  20. type: String,
  21. required: [true, 'Email is required and must be unique'],
  22. unique: true,
  23. trim: true,
  24. validate: [validator.isEmail, 'Invalid email format'],
  25. },
  26. });
  27. export const UserModel = model<User>('User', userSchema);

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

  1. import { Schema, model } from 'mongoose';
  2. import validator from 'validator'
  3. const studentSchema = new Schema<Student>({
  4. id: {
  5. type: Number,
  6. required: [true, 'Student ID must be unique'],
  7. unique: true,
  8. },
  9. username: {
  10. type: String,
  11. required: [true, 'Student username must be unique'],
  12. unique: true,
  13. },
  14. email: {
  15. type: String,
  16. required: [true, 'Email must be unique'],
  17. unique: true,
  18. trim: true,
  19. },
  20. });
  21. export const StudentModel = model<Student>('Student', studentSchema);


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

dkqlctbz

dkqlctbz1#

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

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

字符串

相关问题