Reputation: 615
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
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
And now make the server call.
Upvotes: 1
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