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

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

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

使用 Node、Express、Mongoose

// 模式

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

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

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

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

添加以下代码 -

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

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