Search code examples
node.jsjsonexpressmongoosehateoas

how to add attributes to sub document array in mongoose before sending response, Hateoas


Im having problem to add Hateoas links to my Api when i send the response. When i get to a specific owners doglist and try to get a specific dog (sub document) i can show the dog, but cant add attributes to display when sending the response (i dont want to add the hateoas links in the db.

Using Node, Express, Mongoose

// schema

let mongoose = require('mongoose')
let Schema = mongoose.Schema

// Dog Schema
let dogSchema = new Schema({
  name: { type: String, required: true },
  ownerID: { type: String, required: true },
  breed: { type: String, required: true },
  gender: { type: String, required: true },
  weight: { type: Number, required: false },
  length: { type: Number, required: false },
  img_src: { type: String, required: true }
})

// Owner Schema
let ownerSchema = new Schema({
  name: { type: String, required: true },
  password: { type: String, required: true },
  dogs: [dogSchema]
})

// Owner object
let Owner = mongoose.model('Owner', ownerSchema)

module.exports = Owner

//router

// GET /owners/:ownerId/Dogs/:dogID (view a specific dog)
    router.get('/owners/:ownerID/dogs/:dogID', (req, res, next) => {
      Owner.findById(req.params.ownerID, (err, owner) => {
        if (err) next(err)

        let dog = owner.dogs.id(req.params.dogID) // the specific dog

        // Add links attribute
        dog.links = [
          { rel: 'self', method: 'GET', href: '/owners/' + owner.id + '/dogs/' + dog.id },
          { rel: 'create', method: 'POST', href: '/owners/' + owner.id + '/dogs/' },
          { rel: 'edit', method: 'PUT', href: '/owners/' + owner.id + '/dogs/' + dog.id },
          { rel: 'delete', method: 'DELETE', href: '/owners/' + owner.id + '/dogs/' + dog.id }
        ]
        res.json(dog)
      })
    }

i cant use .lean() on my query (Owner.findById) because this removes the built in .id() method that i use: owner.dogs.id(req.params.dogID)

so, how do i add my Hateoas links to the res.json?


Solution

  • Before your code - dog.links = [*]

    add following code -

    dog = JSON.parse(JSON.stringify(dog))
    

    And then assign new attributes to your dog parameter.