Reputation: 85765
Been googling around but not really sure what I would call this so have not found any tutorials on it.
Say if I have a json what looks like this
{
"firstName": "jim",
"lastName": "smith",
"identifications": [{
"passport": {
"expiry": "2020-01-01",
"nicknames": ["Jim", "J"]
},
"driverLicense": {
"expiry": "2020-01-01",
"restrictions": ["glasses"]
}
}]
}
I have this but I don't know how to tackle Identifications. Do I need to make a new schema for it? Or how do I write it. I am also not sure if I need to normilize each of the properties in each one (ie passport has a nickname but driverLicense does not, do I need it in both?)
const CreditCardSchema = mongoose.Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
identifications: ??
});
Upvotes: 0
Views: 38
Reputation: 1226
This should be what you are looking for.
Mongoose schemas can be nested over and over again as much as you like.
Obviously, you can get much more specific with this schema, such as validating the expiry date.
const CreditCardSchema = mongoose.Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
identifications: [
{
expiry: {
type: String,
required: true,
},
nicknames: [String],
restrictions: [String],
}
],
});
Because identifications can have different fields (like nicknames and restrictions) that may not appear on all of them, it would be better to define more schemas for those.
Consider making another model called Identification
and then you can use it like this:
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const CreditCardSchema = mongoose.Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
identifications: [
{
type: ObjectId,
ref: 'Identification',
},
]
});
Once you make it, you can do let Passport = new Identification({ ... })
, and just run CreditCard.identifications.push(Passport)
and boom, they're linked!
Upvotes: 2