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

149
Visualizações
Default values not adding to mongoose Model

So this is an example of my schema I have for a user.

    id: String,
    email: String,
    slug: {
        type: Object,
        phrase: {type: String, default: null},
    },

When I want to define a new user and save that user, I would do the following;

const newUser = new User({
   id: 123,
   username: "CoolUser",
   email: "BillGates@google.com"
});
                
newUser.save();

But this does not save the "slug" object, It was my understanding, that since I a default value for it, it would auto populate with that default value. What can I do to make it auto generate without having to define the whole schema again when saving a user?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You should add default for slug property, and not for his sub-property. Try changing your schema like this:

slug: {
  type: {
    phrase: { type: String },
  },
  default: {
    phrase: null 
  },
},
about 4 years ago · Juan Pablo Isaza Relatório

0

try this:

const subschema = new Schema({
  phrase: {type: String, default: null},
}, { _id: false });

and in your original schema:

  id: String,
  email: String,
  slug: {
    type: subschema,
    default: () => ({})
  },

this should do the trick.

about 4 years ago · Juan Pablo Isaza Relatório

0

const User = new Schema({
    id: String,
    about: {
        bio: String,
        location: String,
        website: String,
        discord: String,
        twitter: String,
        default: {
            bio: "This is a default bio.",
            location: "",
            website: "",
            discord: "",
            twitter: "",
        }
    }
})

Ok here is the example, I removed some stuff from it just for ease, Basically as you can see I want bio to default to: This is a default bio.

But instead, I get the following error:

    throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
    ^

TypeError: Invalid schema configuration: `This is a default bio.` is not a valid type at path `about.default.bio`. See bit ly / mongoose-schematypes for a list of valid schema types.
about 4 years ago · Juan Pablo Isaza 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