Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

same result:

 "social" : [ ]

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading