Mongoose find 查询返回json数据处理方式(mongo查找)硬核推荐

随心笔谈3年前发布 admin
251 0 0

文章摘要

本文介绍了两个JavaScript数组方法:`findById`和`copyDataModal`。 1. `findById`方法用于查找一个或多个文档。该方法使用`find`接口,可以接受一个数组作为查找条件,通过`$in`操作符匹配文档的 `_id`字段。如果提供数组,会遍历所有文档;否则,仅查找单个文档。代码中使用了`await`进行异步操作,并在错误情况下抛回`HttpException`。 2. `copyDataModal`方法用于复制数据。该方法首先通过`findById`找到文档,并对文档的属性进行数据掩码处理(`dataMasking`),然后生成需要添加的数据(`aDataMasking`)。需要注意的是,代码中缺少`return`语句,可能导致执行异常。 文章整体展示了如何结合异步操作和错误处理实现数据查找和复制功能,同时提到了潜在的实现问题。


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
}

© 版权声明

相关文章