Rytter
Rytter

Reputation: 13

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() returns

So, I want get only _doc object instead it all when return await MyModel.save()

Upvotes: 1

Views: 2454

Answers (2)

Pawan Bishnoi
Pawan Bishnoi

Reputation: 2127

Then try like this

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

Upvotes: 0

Matt
Matt

Reputation: 74670

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.

Upvotes: 5

Related Questions