【问题标题】:Mogoose: Check if fields exist in schema before updating a documentMongoose:在更新文档之前检查模式中是否存在字段
【发布时间】:2019-12-12 18:59:32
【问题描述】:

我有一个这样的集合模型:

const Task = mongoose.model('Task', {
  description: {
    type: String,
    trim: true,
    required: true
  },
  completed: {
    type: Boolean,
    default: false
  }
})

目前,当用户尝试使用 API 更新文档时,任何不在架构中的字段都将被忽略,并且文档将被更新。如果用户使用数据库中不可用的字段向 API 发送更新请求,我想抛出错误。

如果我在数据库中有一个 ID 为 12345 的任务:

{
  _id: 12345,
  description: "Buy cheese."
  completed: false
}

并且用户向 API 发送更新查询以执行任务:

id = '12345'
updates = {
  description: 'Buy Milk',
  due: '1 Week' //<-- Invalid Field
}

我使用这个对象来更新文档:

await Task.findByIdAndUpdate(id, updates)

mongoose 完全忽略无效的due 字段并使用新的description 字段更新文档。

有没有一种干净的方法来避免这种无效的更新请求?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

我找到了一种方法是:

const params = Object.keys(req.body) // req.body is the updates coming from API
const allowedMethods = ["completed", "description"];
const isValidOperation = params.every((param) => allowedMethods.includes(param));

if (!isValidOperation) {
   return res.status(400).send({ error: "invalid update" });
}

【讨论】:

    【解决方案2】:
    While updating add in criteria the key that comes from the front end with $exists if it's not found in database update will not return any data and you can throw an error in that case.
    
    criteria will be {_id:id};
    update will be {description: 'Buy Milk'};
    if(payload.due){
       criteria.due:{$exists:true},
       update.due=payload.due
    }
    

    让 updatedData= 等待 Task.update(criteria,update) if(updatedData.n== 0) throw error 参数无效

    // https://docs.mongodb.com/manual/reference/method/db.collection.update/ 而且这只使用一个查询

    【讨论】:

    • 我认为这个答案不能解决我的问题。或者我不明白你的建议。
    • 您需要检查无效键是否存在于查询中,而更新如果存在,它将更新文档,否则它不会更新文档,如果在更新查询时没有匹配,您将知道发送的键无效,可以在响应正文中发送错误
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2019-03-04
    • 2023-03-07
    • 2017-09-28
    • 2016-08-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多