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" : [ ]
2
Answers
Since
social
is an array ofobjects
. Shouldn’t you be doingRight now you are trying to access property on object, but social is an array of objects
Are you sure that you really want
social
field to be an array? Since it storesfacebook
andtwitter
accounts, it is logical that each user will have only one of these accounts. In that case, it is better if you definesocial
to be object with nested properties. That is easier to maintain and it will work with your code.If you really need
social
field to be an array, you can change your code like this: