Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda