2

If I have a collection defined as,

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

How can I query for all documents, but replace every password into asterisks?

Something like,

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

Is this possible?

1 Answer 1

3

You cannot do this with find() query as it is only used to retrieve data instead can use aggregate for this with a $addFields stage.

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

console.log({ users })

MongoPlayground

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to avoid hardcoding the asterisks and know exactly the length of password?
You want the asterisk as per password's length?
Yes, without sending a hardcoded value of *********** to the front end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.