Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

407
Vistas
How to return specific object values related to privacy values?

I have this mongoose model:

var user = new Schema({
email   : {type: String},
firstName: {type: String},
lastName: {type: String},
username: {type:String},
password: {type:String},
privacy : {
  displayEmail: {type: Boolean, default: true},
  displayUsername: {type:Boolean: default: true},
  displayfirstName: {type:Boolean: default: true},
  displaylastName: {type:Boolean: default: true}
})

Let's assume that the user sets the value of displayEmail abd displayLastName to false.

Then, I have a simple GET request that returns a json object with all the users details. How can I query mongo to return only the fields that have true in the privacy object? If displayfirstName is true, then the firstName value should be returned.

Update

var user = new Schema({
email     : {type: String},
firstName : {type: String},
lastName  : {type: String},
username  : {type:String},
password  : {type:String},
privacy : {
  displayEmail     : {type: Boolean, default: true},
  displayUsername  : {type:Boolean, default: true},
  displayfirstName : {type:Boolean, default: true},
  displaylastName  : {type:Boolean, default: true},
  displayAddress   : {type: Boolean, default: true}, // new 
  displayPhone     : {type: Boolean, default: true}  // new
},
extraInfo : {
     userAddress : {type:String},  // new
     userPhone   : {type: String}  // new
  }
})

How i can conditionally check the address and phone field?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The only way I can think of is through an aggregation pipeline that has a $project operator with a $cond expression that evaluates the condition and returns the value of one of the other two expressions depending on the logic evaluated.

Take for instance, running the following pipeline will give you a document that displays all the fields but their values depend on what the display subdocument fields have; if it's true then the actual value is returned otherwise a null value is returned:

User.aggregate([
    {
        "$project": {
            "email": {
                "$cond": ["$privacy.displayEmail", "$email", null]
            },
            "firstName": {
                "$cond": ["$privacy.displayfirstName", "$firstName", null]
            },
            "lastName": {
                "$cond": ["$privacy.displaylastName", "$lastName", null]
            },
            "username": {
                "$cond": ["$privacy.displayUsername", "$username", null]
            }
        }
    }
]).exec(function(err, users){
    if (err) throw err;
    console.log(JSON.stringify(users, null, 4));
})

UPDATE

Following up your other question from the comments, to conditionally check for the address and phone fields AND filter the collection using the id from a GET parameter, run the pipeline with a $match operator which acts as a query and then add the extra info fields conditional display in your $project:

var userId = mongoose.Schema.Types.ObjectId(req.parameter.userId);

User.aggregate([
    { "$match": { "_id": userId } },
    {
        "$project": {
            "email": {
                "$cond": ["$privacy.displayEmail", "$email", null]
            },
            "firstName": {
                "$cond": ["$privacy.displayfirstName", "$firstName", null]
            },
            "lastName": {
                "$cond": ["$privacy.displaylastName", "$lastName", null]
            },
            "username": {
                "$cond": ["$privacy.displayUsername", "$username", null]
            },
            "userAddress": {
                "$cond": ["$privacy.displayAddress", "$extraInfo.userAddress", null]
            },
            "userPhone": {
                "$cond": ["$privacy.displayPhone", "$extraInfo.userPhone", null]
            }
        }
    }
]).exec(function(err, users){
    if (err) throw err;
    console.log(JSON.stringify(users, null, 4));
})
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda