猫鼬查找查询的所有字段(忽略选择)

时间:2019-09-25 10:27:51

标签: node.js mongoose dynamic-programming

我目前正在将Mongoose用于生产中的项目,现在我们要匿名化数据库。我做了一个脚本,可以对所有数据库中的数据进行匿名处理,但是我遇到了问题。 在我的架构中,我有一些selected=false字段。 例如,在我的用户架构中,默认情况下未选择password字段,因为我不想执行find查询并将其错误返回给客户端。

不管我的模式如何,我都会执行以下步骤:

  1. 获取模型的所有文档:const documents = await model.find()
  2. 遍历每个文档:for (const doc of documents)
  3. 在文档上调用一个函数:const res = await func(doc)
  4. 保存结果:await res.save()

由于我的脚本是通用的,因此我可以从对象中获取模型和函数,以便能够轻松添加新集合以在脚本中进行无生命化:

const anonymizeFunctions = [
  {
    model: models.UserModel,
    func: document => {
      document.password = 'somePass'
      return document
    }
  },
  ...
]

最后,它看起来像这样:

const anonymizeFunctions = [
  {
    model: models.UserModel,
    func: document => {
      document.password = 'somePass'
      return document
    }
  },
  ...
]

// This function is call with each element of anonymizeFunctions 
// with the model and func property of the object
async function anonymizeCollection(model, func) {
  const documents = await model.find()
  for (const doc of documents) {
    const res = await func(doc)
    await res.save()
  }
}

我的问题是find不仅针对用户而且针对所有其他型号也是如此,因此我不能不幸地使用model.find().select('+password')。我需要完全忽略select指令,无论如何查询都需要返回模型的所有字段。

0 个答案:

没有答案