如何为单个查询禁用 sanitizeFilter

问题描述 投票:0回答:1

为了防止DB注入,我设置了

mongoose.set('sanitizeFilter', true)

但是,我需要在设置该选项之前工作的猫鼬模型上执行以下查询:

await Inventory.updateMany(
  {
    $and: [
      { date: { $gte: new Date(checkIn) } },
      { date: { $lt: new Date(checkOut) } },
      { roomTypeId: room.roomTypeId },
    ],
  },
  {
    $inc: { inventory: -room.quantity },
  }
)

所以我首先用以下方法清理个人价值观:

mongoose.sanitizeFilter(checkIn)
mongoose.sanitizeFilter(checkOut)
mongoose.sanitizeFilter(room.quantity)

然后我试了:

await Inventory.updateMany(
  {
    $and: [
      { date: { $gte: new Date(checkIn) } },
      { date: { $lt: new Date(checkOut) } },
      { roomTypeId: room.roomTypeId },
    ],
  },
  {
    $inc: { inventory: -room.quantity },
  },
  { sanitizeFilter: false } // <-- added this
)

那没用,所以我试了:

await Inventory.updateMany(
  {
    $and: [
      { date: { $gte: new Date(checkIn) } },
      { date: { $lt: new Date(checkOut) } },
      { roomTypeId: room.roomTypeId },
    ],
  },
  {
    $inc: { inventory: -room.quantity },
  },
).setOptions({ sanitizeFilter: false }) // <-- added this

和:

await Inventory.updateMany(
  {
    $and: [
      { date: mongoose.trusted({ $gte: new Date(checkIn) }) },
      { date: mongoose.trusted({ $lt: new Date(checkOut) }) },
      { roomTypeId: room.roomTypeId },
    ],
  },
  {
    $inc: { inventory: -room.quantity },
  },
)

所有这些都会导致类似的错误:

CastError:模型“库存”的路径“日期”处的值“{'$gte':2023-04-08T00:00:00.000Z}”(类型对象)转换为日期失败

如何在启用

sanitizeFilter
的情况下执行此操作?

mongodb mongoose sanitize
1个回答
0
投票

使用

trusted
您可以指定
sanitizeFilter
应该跳过的表达式:

await Inventory.updateMany(
    {
      $and: [
        { date: mongoose.trusted({ $gte: new Date(checkIn) }) },
        { date: mongoose.trusted({ $lt: new Date(checkOut) }) },
        { roomTypeId: room.roomTypeId },
      ],
    },
    {
      $inc: { inventory: -room.quantity },
    }
  )
© www.soinside.com 2019 - 2024. All rights reserved.