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

106
Vistas
Failed to update single property by mongoose

Frist I have read and try the solution in the post of mongoose-and-partial-select-update. However when I try to use the traditional style, query would work.

My schema:

var userSchema = mongoose.Schema({
    local: {
        email: {
            type: String,
            index: {
                unique: true,
                dropDups: true
            }
        },
        password: String,
        displayName: String,
        avatar: {
            type: String,
            default: "./img/user.png"
        },
        role: {
            type: String,
            default: "student"
        },
        ask_history: [
            {
                question_id: {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: 'questionAnswer'
                },
                favorite: Boolean,
                ask_time: Date
            }
        ],
        interest: [String]
    }
})

Working Update function:

User.findById(id, function(err, User) {
            if (err) {
                throw done(err);
            }
            if (!User) {
                return;
            }
            User.local.role = "admin";
            User.save(function(err, updatedUser) {
                if (err) {
                    throw err
                } else {
                    //good
                }
            })
        });

However if I do this:

User.update({_id : id},
  {$set{
      local:{role:"admin"}
     }
  },function(...){...}
});

Code above will overwrite user into:

{
  _id : "...",
  local: {
          role : "admin"
         }
}

I read that $ will make the update only changing property, where I did wrong?

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

0

The positional operator $ works with array of subdocuments.

In your case you have a single sub-document, so the following should work:

User.update({_id : id},
    { $set
        {
            "local.role": "admin"
        }
    }, function(...){...}
});
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