Mongoose find 查詢返回json數(shù)據(jù)處理方式
前言
Mongoose find方法,打印看著返回的是json數(shù)據(jù),實際返回的是Mongoose實例,為了方便自定義拓展或操作鏈式操作。
需求
如圖復制按鈕,點擊復制按鈕填寫信息,復制出有相同屬性的數(shù)據(jù)模型;
處理思路
傳參:{id:"", //被復制的數(shù)據(jù)模型id ...(其他填寫參數(shù)) };通過id查詢被復制數(shù)據(jù)模型所有數(shù)據(jù),刪除數(shù)據(jù)id,刪除屬性id,其他填寫參數(shù)覆蓋,然后寫庫。
遇到問題
代碼如下,執(zhí)行時,直接報堆棧溢出,獲取的modalData不是json數(shù)據(jù)不能modalData.props或{...modalData}
/** * 根據(jù)id查詢數(shù)據(jù)模型 * @param id 數(shù)據(jù)模型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; } /** * 復制數(shù)據(jù)模型 * @param dataModel 數(shù)據(jù)模型 */ 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))處理一遍
缺點:數(shù)據(jù)復雜時會導致部分數(shù)據(jù)丟失或轉義
2.Mongoose find 查詢時用.toObject()或.toJSON()將數(shù)據(jù)轉換為json,修改findById方法的return;
return res?res.toObject():res return res?res.toJSON():res
3.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 }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MongoDB運行狀態(tài)監(jiān)控、性能分析工具mongostat詳解
這篇文章主要介紹了MongoDB運行狀態(tài)監(jiān)控、性能分析工具mongostat詳解,mongostat是mongdb自帶的狀態(tài)檢測工具,在命令行下使用,它會間隔固定時間獲取mongodb的當前運行狀態(tài),并輸出,本文詳細講解了它的使用,需要的朋友可以參考下2015-07-07Windows系統(tǒng)下安裝MongoDB與Robomongo環(huán)境詳解
這篇文章主要給大家介紹了在Windows系統(tǒng)下安裝MongoDB與Robomongo環(huán)境的相關資料,文中介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04MongoDB的備份(mongodump)與恢復(mongorestore)
在使用MongoDB時,數(shù)據(jù)備份與恢復是非常重要的一環(huán),以防止數(shù)據(jù)丟失或意外刪除,本文就來介紹一下MongoDB的備份(mongodump)與恢復(mongorestore),感興趣的可以了解一下2023-12-12centos離線安裝mongodb-database-tools方法詳解
這篇文章主要介紹了centos離線安裝mongodb-database-tools方法詳解的相關資料,需要的朋友可以參考下2022-11-11MongoDB數(shù)據(jù)庫文檔操作方法(必看篇)
下面小編就為大家?guī)硪黄狹ongoDB數(shù)據(jù)庫文檔操作方法(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07MongoDB如何正確中斷正在創(chuàng)建的索引詳解
這篇文章主要給大家介紹了關于MongoDB如何正確中斷正在創(chuàng)建的索引的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12