服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - Mongoose find 查询返回json数据处理方式

Mongoose find 查询返回json数据处理方式

2023-04-06 18:09yolo莹 MongoDB

这篇文章主要介绍了Mongoose find 查询返回json数据处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

前言

Mongoose find方法,打印看着返回的是json数据,实际返回的是Mongoose实例,为了方便自定义拓展或操作链式操作。

需求

如图复制按钮,点击复制按钮填写信息,复制出有相同属性的数据模型;

Mongoose find 查询返回json数据处理方式

处理思路

传参:{id:"", //被复制的数据模型id ...(其他填写参数) };通过id查询被复制数据模型所有数据,删除数据id,删除属性id,其他填写参数覆盖,然后写库。

遇到问题

代码如下,执行时,直接报堆栈溢出,获取的modalData不是json数据不能modalData.props或{...modalData}

Mongoose find 查询返回json数据处理方式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  /**
   * 根据id查询数据模型
   * @param id 数据模型id
   */
  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;
  }
 
/**
   * 复制数据模型
   * @param dataModel 数据模型
   */
  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
  }

解决方案

1.modalData=JSON.parse(JSON.stringify(modalData))处理一遍

缺点:数据复杂时会导致部分数据丢失或转义

2.Mongoose find 查询时用.toObject()或.toJSON()将数据转换为json,修改findById方法的return;

?
1
2
return res?res.toObject():res
return res?res.toJSON():res

3.Mongoose find 查询后.lean().exec()链式处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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
  }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_41438582/article/details/125184440

延伸 · 阅读

精彩推荐