这篇文章主要介绍“MonGoose find查询返回JSON数据处理的方法是什么”,在日常操作中,相信很多人在Mongoose find查询返回json数据处理的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好
这篇文章主要介绍“MonGoose find查询返回JSON数据处理的方法是什么”,在日常操作中,相信很多人在Mongoose find查询返回json数据处理的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Mongoose find查询返回json数据处理的方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
如图复制按钮,点击复制按钮填写信息,复制出有相同属性的数据模型;
传参:{id:"", //被复制的数据模型id ...(其他填写参数) };通过id查询被复制数据模型所有数据,删除数据id,删除属性id,其他填写参数覆盖,然后写库。
代码如下,执行时,直接报堆栈溢出,获取的modalData不是json数据不能modalData.props或{...modalData}
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 }
modalData=JSON.parse(JSON.stringify(modalData))处理一遍
缺点:数据复杂时会导致部分数据丢失或转义
Mongoose find 查询时用.toObject()或.toJSON()将数据转换为json,修改findById方法的return;
return res?res.toObject():resreturn res?res.toJSON():res
Mongoose find 查询后.lean().exec()链式处理
async findById(id: string | string[]) { let res try { if (Array.isArray(id)) { res = await this.dataModel.find({ _id: { $in: id } }).lean().exec() } else { res = await this.dataModel.findById(id).lean().exec() } } catch (error) { throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR) } return res }
到此,关于“Mongoose find查询返回json数据处理的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!
--结束END--
本文标题: Mongoose find查询返回json数据处理的方法是什么
本文链接: https://www.lsjlt.com/news/355586.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0