简体   繁体   中英

How return only document created after perform save() with mongoose

When I use return await Model.save() they return a lot of data. 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()

Document.prototype.toObject() converts a mongoose document into the plain javascript object representation.

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
  • aliases apply all aliases if virtuals=true , defaults to true
  • virtuals apply virtual getters (can override getters option), defaults to false
  • minimize remove empty objects, defaults to true
  • transform a transform function to apply to the resulting document before returning
  • depopulate depopulate any populated paths, replacing them with their original refs, defaults to false
  • versionKey whether to include the version key, defaults to true
  • flattenMaps convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false
  • useProjection set to true to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has select: false in the schema.

Then try like this

let res = await Model.save();
return res._doc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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