I have the following mongoose schema:
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
extraData: {
brand: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
quantity: {
type: Number,
required: true,
minlength: 1,
maxlength: 10
},
required: true
}
});
However when i execute it I get the following error: "TypeError: Invalid schema configuration: True
is not a valid type at path extraData.required
". How can I require the extraData?
Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
Nested JSON is simply a JSON file with a fairly big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
As mentioned by user whoami, mongoose only sets defaults on insert. If you are using mongoose 4. x and up and MongoDB 2.4. 0 and up you can opt-in to setting default values on update too.
Update: You can use the Subdocument apporach
const extraDataSchema = new mongoose.Schema({
brand: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
quantity: {
type: Number,
required: true,
minlength: 1,
maxlength: 10
}
});
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
extraData: {
type: extraDataSchema, required: true
}
});
Check out the Mongoose documentation, In this link you can find an explanation on how to add required
to nested properties().
I believe you will need a sub-schema for the nested properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With