前言
mongoose find方法,打印看着返回的是json数据,实际返回的是mongoose实例,为了方便自定义拓展或操作链式操作。
需求
如图复制按钮,点击复制按钮填写信息,复制出有相同属性的数据模型;

处理思路
传参:{id:"", //被复制的数据模型id ...(其他填写参数) };通过id查询被复制数据模型所有数据,删除数据id,删除属性id,其他填写参数覆盖,然后写库。
遇到问题
代码如下,执行时,直接报堆栈溢出,获取的modaldata不是json数据不能modaldata.props或{...modaldata}

/**
* 根据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;
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
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论