saintPez
saintPez

Reputation: 15

is there a way to find and return a property if it has a specific value?

What I want is that in users query it returns the email data whenever private is false.

this is my scheme

const userSchema = new Schema({
  email: {
    private: {
      type: Boolean,
      default: false,
    },
    data: {
      type: String,
      unique: true,
      required: true,
    },
  },
  password: {
    type: String,
    required: true,
  }
})

I tried to do it this way, but it doesn't work because it is not dynamic.

const user = await User.find({}, '-email.data')

the result I am looking for is this

[
  { _id: 0, email: { private: true } },
  { _id: 1, email: { private: false, data: '[email protected]' } }
]

Upvotes: 1

Views: 33

Answers (1)

turivishal
turivishal

Reputation: 36114

Try $cond operator, check if email.private is true then return only private property otherwise full email object

const user = await User.find({},
{
  email: {
    $cond: [
      { $eq: ["$email.private", true] },
      { private: true },
      "$email"
    ]
  }
})

Playground

Upvotes: 2

Related Questions