morto
morto

Reputation: 73

Node.js MongoDb with mongoose custom json response

I have a collection that replays with the data below when i get all documents. But i would like to add a custom "grouping" to it so it looks like example 2 below. And i though you could do it by using Population but im not getting it to work..

Original json

[
      {
      "id" : "...",
      "category" : "...",
      "header" : "...",
      "body" : "..."
   },
      {
      "id" : "...",
      "category" : "...",
      "header" : "...",
      "body" : "..."
   }
]

What i want:

{
  "offers" : [ {
    "id" : "...",
    "category" : "...",
    "header" : "...",
    "body" : "..."
     },
     {
    "id" : "...",
    "category" : "...",
    "header" : "...",
    "body" : "..."
     }]
}

Upvotes: 0

Views: 1016

Answers (2)

Unknown
Unknown

Reputation: 436

By using the lodash module in npm, we can select the required felid in JSON respone

   import mongoose from 'mongoose'
   import pick from 'lodash/pick'



    UserSchema.methods.toJSON = function () 
       let user = this
       let userObject = user.toObject()
       return pick(userObject, ['_id', 'email'])
       }

Upvotes: 0

robertklep
robertklep

Reputation: 203419

Well, you can just create that object yourself:

var obj = { offers : results };

(where results is your Mongoose result set).

Upvotes: 1

Related Questions