【问题标题】:Mongoosejs - Can I modify docs in post query middleware of 'find'?Mongoosejs - 我可以在“查找”的后查询中间件中修改文档吗?
【发布时间】:2018-11-29 03:47:48
【问题描述】:

我使用的是 mongoose.js 版本 5.1.6。有没有办法在查询find 后自动执行 doc.toObject()?我不确定我是否可以在find的中间件中做到这一点。

schema.post('find', function(docs) {
  // Can I change the docs that return by find() by modify the docs here?
})

【问题讨论】:

  • “我可以通过修改此处的文档来更改 find() 返回的文档吗?” - 你...尝试过吗?
  • 您可以将.lean() 链接到您的查询。 toObject() 处理文档,.lean() 处理查询。 mongoosejs.com/docs/api.html#query_Query-lean 当然,你不能在那些物体上使用任何猫鼬模型的东西......
  • @ippi 是的,但我使用toObject(),因为它可以转换原始数据,例如删除一些敏感信息
  • stackoverflow.com/a/29988752/1497533 .post('init' 似乎可以解决问题
  • 似乎使用 .select 告诉数据库服务器根本不返回该敏感信息会更好——但您可以使用 post init 或 post find

标签: node.js mongoose


【解决方案1】:

是的,你可以。你必须做这样的事情

schema.post('find', function(docs) {
  // Here you can modify the doc returned by find
doc._doc.<some attribute> = 'asdasdasd'
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-15
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多