Oussama Bouchikhi
Oussama Bouchikhi

Reputation: 615

MongoDB/Mongoose schema unique not working

I want to create a city with name and some other fields, the name should be unique but I am able to create other cities with the same name. How do I make the name unique in mongoose schema in order to obtain unique cities in the database?

cities.service.ts

@Injectable()
export class CitiesService {

  constructor(
    @InjectModel('City') private readonly cityModel: Model<City>,
  ) {}

  async createCity(createCityDto: CreateCityDto) {
      const { name } = createCityDto;
      const city = new this.cityModel({ name });
      await city.save();
      return city;
  }
}

cities.controller.ts

@Post()
  @ApiCreatedResponse({ description: 'Create a new city' })
  @ApiBody({ type: CreateCityDto })
  @ApiConflictResponse({ description: 'This city already exists' })
  createCity(@Body() createCityDto: CreateCityDto) {
    return this.citiesService.createCity(createCityDto);
  }

city.model.ts

import * as mongoose from 'mongoose';

export const CitySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
  }
});

export interface City {
  id: mongoose.Schema.Types.ObjectId;
  name: string;
}

Upvotes: 0

Views: 3986

Answers (2)

P K Dhee Taal
P K Dhee Taal

Reputation: 23

In most cases, this happens when you already have multiple data with the same value you are applying uniqueness in the table. You can take the following steps to fix it

  1. i. drop the database
  2. ii. restart the server

And now make the server call.

Upvotes: 1

BrettEvade
BrettEvade

Reputation: 71

Make sure to set autoIndex on your connection to the database. Also make sure that you data doesn't already have mess-ups. If you already have 2 names that are not unique in your database it will not follow the option.

Upvotes: 4

Related Questions