[英]How return only document created after perform save() with mongoose
When I use return await Model.save()
they return a lot of data.当我使用
return await Model.save()
时,它们会返回大量数据。 There is a way to return the document only?有没有办法只返回文件?
Code:代码:
async (data) =>{
const charData = new MyModel({
steamId: data.steam,
phone: data.phone,
registration: data.registration,
})
return await MyModel.save()
}
I've searched in many websites but I didnt find any example using async functions.我在很多网站上搜索过,但没有找到任何使用异步函数的示例。
There is a example that MyModel.save()
are returning:有一个
MyModel.save()
返回的例子:
So, I want get only _doc object instead it all when return await MyModel.save()
所以,我只想在
return await MyModel.save()
时获取 _doc object 而不是全部
Document.prototype.toObject()
converts a mongoose document into the plain javascript object representation. Document.prototype.toObject()
将 mongoose 文档转换为普通的 javascript object 表示。
async (data) =>{
const charData = new MyModel({
steamId: data.steam,
phone: data.phone,
registration: data.registration,
})
await charData.save()
return charData.toObject({ getters: true })
}
Note the options which affect how the document is represented:请注意影响文档表示方式的选项:
getters
apply all getters (path and virtual getters), defaults to falsegetters
应用所有 getters(路径和虚拟 getters),默认为 falsealiases
apply all aliases ifvirtuals=true
, defaults to true如果
virtuals=true
,aliases
应用所有别名,默认为 truevirtuals
apply virtual getters (can override getters option), defaults to falsevirtuals
应用虚拟 getters(可以覆盖 getters 选项),默认为 falseminimize
remove empty objects, defaults to trueminimize
移除空对象,默认为 truetransform
a transform function to apply to the resulting document before returningtransform
转换 function 以在返回之前应用于生成的文档depopulate
depopulate any populated paths, replacing them with their original refs, defaults to falsedepopulate
depopulate 任何已填充的路径,将它们替换为原始引用,默认为 falseversionKey
whether to include the version key, defaults to trueversionKey
是否包含版本密钥,默认为 trueflattenMaps
convert Maps to POJOs.flattenMaps
将地图转换为 POJO。 Useful if you want to JSON.stringify() the result of toObject(), defaults to false如果你想 JSON.stringify() toObject() 的结果很有用,默认为 false
useProjection
set totrue
to omit fields that are excluded in this document's projection.useProjection
设置为true
以忽略本文档投影中排除的字段。 Unless you specified a projection, this will omit any field that hasselect: false
in the schema.除非您指定投影,否则这将忽略架构中具有
select: false
的任何字段。
Then try like this然后像这样尝试
let res = await Model.save();
return res._doc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.