我想創建一個帶有名稱和其他一些欄位的城市,名稱應該是唯一的,但我可以創建具有相同名稱的其他城市。如何使名稱在 mongoose 模式中唯一以獲得資料庫中的唯一城市?
城市.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;
}
}
city.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;
}
uj5u.com熱心網友回復:
確保在與資料庫的連接上設定 autoIndex。還要確保您的資料沒有混亂。如果您的資料庫中已有 2 個不唯一的名稱,則不會遵循該選項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391899.html
上一篇:MongoDB管道條件計數
