文章摘要
该文章介绍了使用MongoDB的异步查询功能,提供了两个主要操作:查找和复制数据。首先,`findById`函数可以接受单个或多个id,通过`find`或`findById`方法查找对应的文档,并在异常情况下抛回内部服务器错误。其次,`copyDataModal`函数用于复制数据,它通过`findById`获取目标文档后,对属性进行数据掩码处理,然后创建新文档并返回。整个过程支持异步操作,提高了性能。
async findById(id: string | string[]) {
let res
try {
if (Array.isArray(id)) {
res=await this.dataModel.find({ _id: { $in: id } })
} else {
res=await this.dataModel.findById(id)
}
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
}
return res;
}
async findById(id: string | string[]) {
let res
try {
if (Array.isArray(id)) {
res=await this.dataModel.find({ _id: { $in: id } })
} else {
res=await this.dataModel.findById(id)
}
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
}
return res;
}
async copyDataModal(dataModel: CopyDataModelDto) {
let res
try {
const { id }=dataModel
const modalData=await this.findById(id)
if (modalData) {
modalData.props=(modalData.props || []).map((ele: any)=> {
return dataMasking(ele, [‘_id’])
})
const addData=dataMasking({ …modalData, …dataModel }, [‘_id’, ‘id’, ‘__v’])
// res=await this.add(addData)
res=addData
}
} catch (error) {
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
}
return res
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。



