Mongoose find 查詢返回json數(shù)據(jù)處理方式
前言
Mongoose find方法,打印看著返回的是json數(shù)據(jù),實際返回的是Mongoose實例,為了方便自定義拓展或操作鏈?zhǔn)讲僮鳌?/p>
需求
如圖復(fù)制按鈕,點(diǎn)擊復(fù)制按鈕填寫信息,復(fù)制出有相同屬性的數(shù)據(jù)模型;

處理思路
傳參:{id:"", //被復(fù)制的數(shù)據(jù)模型id ...(其他填寫參數(shù)) };通過id查詢被復(fù)制數(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;
}
/**
* 復(fù)制數(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))處理一遍
缺點(diǎn):數(shù)據(jù)復(fù)雜時會導(dǎo)致部分?jǐn)?shù)據(jù)丟失或轉(zhuǎn)義
2.Mongoose find 查詢時用.toObject()或.toJSON()將數(shù)據(jù)轉(zhuǎn)換為json,修改findById方法的return;
return res?res.toObject():res return res?res.toJSON():res
3.Mongoose find 查詢后.lean().exec()鏈?zhǔn)教幚?/p>
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
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
mongodb基礎(chǔ)之用戶權(quán)限管理實例教程
這篇文章主要給大家介紹了關(guān)于mongodb基礎(chǔ)之用戶權(quán)限管理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
Pycharm連接MongoDB數(shù)據(jù)庫安裝教程詳解
這篇文章主要介紹了Pycharm連接MongoDB數(shù)據(jù)庫安裝教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
為MongoDB數(shù)據(jù)庫注冊windows服務(wù)
這篇文章介紹了為MongoDB數(shù)據(jù)庫注冊windows服務(wù)的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

