I have following mongoose schema –
const UserSchema = new mongoose.Schema({
name: {type: String, required: true, trim: true},
email: {type: String, required: true, trim: true},
password: {type: String, required: true, trim: true},
addresses: [{
type: {type: String, required: true, trim: true},
pinCode: {type: String, required: true, trim: true},
city: {type: String, required: true, trim: true},
state: {type: String, required: true, trim: true},
landmark: {type: String, required: false, trim: true},
}]
})
only name
, email
and password
are required for registration. User can have more than one address
, and each address
has some required
fields like in flipkart.com/account/addresses user’s account page.
Each address will be stored in addresses
array field in mongodb database.
I want to keep addresses
array [ ]
when user register. address are only provided through user’s account page web page.
But I am getting ValidatorError
because schema of doc inside addresses
array having required fields.
when user register –
{
name: 'rahul',
email: '[email protected]',
password: 'pass123',
addresses: []
}
user is already registered, and then add address
{
name: 'rahul',
email: '[email protected]',
password: 'pass123',
addresses: [
{
type: 'home',
pinCode: '111222',
city: 'city1',
state: 'state1'
},
{
type: 'work',
pinCode: '333444',
city: 'city2',
state: 'state2',
landmark: 'landmark2'
}
]
}
How to achieve above ??
Any help would be appreciated.
3
Answers
I was doing this -
Not passing
addresses: []
, prevent errorValidatorError
You just have to remove required:true field from address array not even required:false.
Just type and trim will the job and required is false by default so you dont have to include it.
Try the below code. Hope this will help you.
And when you will run the above code, you will be able to see a collection and document like this in your DB, as in the below screenshot.
Hope this will help you. For more information please visit this mongoose documentation link.