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

226
Visualizações
Mongoose Remove key(s) from child schema (nested subdocuments)

I have two schemas defined, imageSchema and userSchema. imageSchema has key postedBy: userSchema. Question is shall I remove unused attributes of userSchema (like password) when nested into imageSchema, if so how to do it?

var userSchema = new mongoose.Schema({
  email: String,
  password: String,
  name: String,
}, {versionKey: false})

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema,
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})
...
app.post("/upload-image", async function(req, res){
  if(req.session.user_id) {
    ...
      fileSystem.rename(oldPath, newPath, function(err2){
        getUser(req.session.user_id, function(user){
          delete user.password
          var currentTime = new Date().getTime()
          Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": currentTime,
            "comments": []
          }, function(err2, data){
            res.redirect("/?message=image_uploaded")
          })
...

So after I created a new document of Image, I checked the database, the user field of the new Image has the attribute of password, which is not desired. "delete user.password" seems not working. How should I delete this attribute? Shall I do it when defining the imageSchema, or remove it when posting the data (the app.post part)?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

This can be done is multiple ways. The way i like is to exclude the field from schema and also exclude while insertion.

Exclude from schema

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema.pick(["email", "name"]), // this will return schema with only email and name from the schema
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})

Exclude while inserting

we are omitting the user here before insertion this can be also done with underscore/lodash _.omit(user, 'password')

getUser(req.session.user_id, function({password, ...user}){
         Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": Date.now(),
            "comments": []
          })
}
about 4 years ago · Santiago Gelvez 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