mongodb/mongoose:如果来自nestjs的数据不为null,则保存唯一值



我正在尝试将数据保存在MongoDB中。当数据不为空时,我想存储唯一的数据。但是,我希望在唯一标识符中允许多个null值。

我的示例模式:

@Schema()
export class Contact extends Document {
@Prop({ unique: true, sparse: true, require: true })
email: string;

@Prop({ default: '+1' })
countryCode: string;
@Prop({ unique: true, sparse: true })
mobile: string;
}

在这种情况下,不需要手机号码。用户可以在提供或不提供手机号码的情况下添加他们的联系信息。如果用户发送的手机号码应该是唯一的。因此,我需要在mobile字段中允许多个null值。但是,当用户提供任何移动电话号码时,该字段应该是唯一的。

空条目的值似乎为null,因此每个没有mobile的条目都会与unique标识符一起崩溃。

有没有办法从数据库层或应用程序层解决这个问题?

我正在使用NestJS来开发我的API。

唯一索引仍然不允许多个字段为null的文档。在MongoDB中保存文档之前,您需要通过删除null字段来转换数据负载。转换管道将帮助您处理此问题。这里有一个可以用于此目的的转换管道:

@Injectable()
export class NullValidationPipe implements PipeTransform {
private isObj(obj: any): boolean {
return typeof obj === 'object' && obj !== null;
}
private dropNull(values) {
Object.keys(values).forEach((key) => {
if (!(key === 'password' || key === '_id')) {
if (this.isObj(values[key])) {
values[key] = this.dropNull(values[key]);
} else if (Array.isArray(values[key]) && values[key].length > 0) {
values[key] = values[key].map((value) => {
if (this.isObj(value)) {
value = this.dropNull(value);
}
return value;
});
} else {
if (values[key] === null || values[key] === undefined) {
delete values[key];
}
}
}
});
return values;
}
transform(values: any, metadata: ArgumentMetadata) {
const { type } = metadata;
if (type === 'param' || type === 'custom') return values;
else if (this.isObj(values) && type === 'body') {
return this.dropNull(values);
}
throw new BadRequestException('Validation failed');
}
}

在控制器中使用此管道,此管道将丢弃所有传入的null字段,这些字段将与请求负载一起提供。

您还可以检查嵌套管道转换文档:https://docs.nestjs.com/techniques/validation

最新更新