【问题标题】:Query MongoDB, replacing one specific field with regex查询 MongoDB,用正则表达式替换一个特定字段
【发布时间】:2020-02-11 10:45:12
【问题描述】:

如果我有一个集合定义为,

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },

如何查询所有文档,但将每个密码都替换为星号?

类似的,

const users = await User.find({
  password: password.replace(/./gi, '*');
})

这可能吗?

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您不能使用find() 查询来执行此操作,因为它仅用于检索数据,而可以将aggregate 用于$addFields 阶段。

    const users = await User.aggregate([
      { "$addFields": {
        "password": {
          "$reduce": {
            "input": { "$range": [0, { "$strLenCP": "$password" }] },
            "initialValue": "",
            "in": {
              "$concat": [
                "*",
                "$$value"
              ]
            }
          }
        }
      }}
    ])
    
    console.log({ users })
    

    MongoPlayground

    【讨论】:

    • 有没有办法避免硬编码星号并准确知道密码的长度?
    • 您想要根据密码长度的星号?
    • 是的,不向前端发送硬编码值***********
    猜你喜欢
    • 2013-10-23
    • 2016-03-02
    • 2016-03-24
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多