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

305
Vistas
How to save an array of strings using mongoose schema

I have this schema to represent a user:

const UserSchema = mongoose.Schema({
    username: {
        type: String,
        required: false
    },
    social: [{
        facebook: {
            type: String,
            required: false
        },
        twitter: {
            type: String,
            required: false
        }
    }]
});

how can I save values using this schema? What I am doing so far:

user.username = username;
user.social['facebook'] = facebook;
user.social['twitter'] = twitter;

await user.save();

this works for username but social is still an empty array. I also tried

user.social.facebook = facebook;
user.social.twitter = twitter;

same result:

 "social" : [ ]
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Since social is an array of objects. Shouldn't you be doing

user.social[0].facebook = facebook;
user.social[0].twitter = twitter;

Right now you are trying to access property on object, but social is an array of objects

over 4 years ago · Santiago Trujillo Denunciar

0

Are you sure that you really want social field to be an array? Since it stores facebook and twitter accounts, it is logical that each user will have only one of these accounts. In that case, it is better if you define social to be object with nested properties. That is easier to maintain and it will work with your code.

social: {
  facebook: { type: String, required: false },
  twitter: { type: String, required: false }
}

If you really need social field to be an array, you can change your code like this:

user.username = username;
user.social[0] = {
  'facebook': facebook,
  'twitter': twitter,
};

await user.save();
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