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;
}
CodePudding user response:
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.