[英]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" : [ ]
Since social
is an array of objects
.由于
social
是一组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现在你正试图访问 object 上的属性,但 social 是一个对象数组
Are you sure that you really want social
field to be an array?您确定您真的希望
social
field 成为一个数组吗? Since it stores facebook
and twitter
accounts, it is logical that each user will have only one of these accounts.由于它存储
facebook
和twitter
帐户,因此每个用户将只有一个这些帐户是合乎逻辑的。 In that case, it is better if you define social
to be object with nested properties.在这种情况下,最好将
social
定义为具有嵌套属性的 object。 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:如果你真的需要
social
field 是一个数组,你可以像这样改变你的代码:
user.username = username;
user.social[0] = {
'facebook': facebook,
'twitter': twitter,
};
await user.save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.