如何调整Mongoose基础架构中的findAll()_ id或id param

时间:2014-07-17 12:50:49

标签: node.js coffeescript mongoose

我已经创建了一个Mongoose基础架构,负责加密_id并将其作为基于id的基础架构返回给我的基于restify的API。

BaseSchema = () ->

  Schema.apply @, arguments

  # Ensure virtual fields are serialised.
  @set 'toJSON', {

    virtuals: true

  }

  @set 'toObject', {

    virtuals: true

  }

  # transform our JSON so its friendly for our API
  @options.toJSON.transform = ( doc, ret, options ) ->

    # remove _id and __v so we dont expose it in the API
    delete ret._id
    delete ret.__v

    return ret

  # encrypted _id in id using a virtual
  @virtual('id')

    .get ->

      id = hashids.encryptHex this._id.toHexString()
      return id 

    .set ( id ) ->

      console.log 'Setting', id
      @_id = mongoose.Types.ObjectId hashids.decryptHex(id) 
      return

  # some default and consistent schema fields
  @add {

      # when the document was created
      createdAt: {

        type: Date,
        default: Date.now

      },

      # when the document was modified
      modifiedAt: {

        type: Date,
        default: Date.now

      }
  }

然后在后续架构中:

PersonSchema = new BaseSchema {}, { id: false }

为了缓解转换我在API查询调用中收到的id的问题,我创建了以下restify中间件:

server.use ( req, res, next ) ->

  if req.params.id

    req.params.id = hashids.decryptHex req.params.id

  next()

这有效,但我对此并不满意。

我想知道是否有一种方法可以处理id的解密和基本模式中_id ObjectId的转换。我希望能够做到:

server.get '/interfaces/:id', ( req, res, next ) ->

  # get the interface based on id
  iface = Interface.findOne { _id: req.params.id } , ( err, iface ) ->

    res.send iface
    next()

_id是findOne {}查询的一部分,因此应在实际查询执行之前进行翻译。

这将很好地集中逻辑。

谢谢!

1 个答案:

答案 0 :(得分:0)

在执行查询之前,您可以使用mongodb的ObjectID将十六进制字符串转换为ObjectID

var ObjectID = require('mongodb').ObjectID;

 :
 :

 var id = ObjectID.createFromHexString(req.params.id);
 iface = Interface.findOne { _id: id } , ( err, iface )