简体   繁体   English

如何仅返回在使用 mongoose 执行 save() 后创建的文档

[英]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()返回的例子: 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 false getters应用所有 getters(路径和虚拟 getters),默认为 false
  • aliases apply all aliases if virtuals=true , defaults to true如果virtuals=truealiases应用所有别名,默认为 true
  • virtuals apply virtual getters (can override getters option), defaults to false virtuals应用虚拟 getters(可以覆盖 getters 选项),默认为 false
  • minimize remove empty objects, defaults to true minimize移除空对象,默认为 true
  • transform a transform function to apply to the resulting document before returning transform转换 function 以在返回之前应用于生成的文档
  • depopulate depopulate any populated paths, replacing them with their original refs, defaults to false depopulate depopulate 任何已填充的路径,将它们替换为原始引用,默认为 false
  • versionKey whether to include the version key, defaults to true versionKey是否包含版本密钥,默认为 true
  • flattenMaps 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 to true to omit fields that are excluded in this document's projection. useProjection设置为true以忽略本文档投影中排除的字段。 Unless you specified a projection, this will omit any field that has select: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM