在发送响应之前,如何在猫鼬中向子文档数组添加属性,Hateoas

时间:2019-02-27 12:58:02

标签: node.js json express mongoose hateoas

发送响应时,我无法将Hateoas链接添加到我的Api。当我到达特定所有者的狗列表并尝试获取特定狗(子文档)时,我可以显示该狗,但是无法添加属性以在发送响应时显示(我不想在数据库中添加hateoas链接。

使用Node,Express,猫鼬

//模式

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

//路由器

// 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)
      })
    }

我无法在查询(Owner.findById)上使用.lean(),因为这删除了我使用的内置.id()方法:owner.dogs.id(req.params.dogID)

那么,如何将Hateoas链接添加到res.json?

1 个答案:

答案 0 :(得分:0)

代码之前-dog.links = [*]

添加以下代码-

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

然后为您的dog参数分配新属性。