const ParentSchema = new Schema({
key1: {type: String, required: true},
key2: {type: String, required: true},
child: {type: [ChildSchema], default: ChildSchema}
})
const ChildSchema = new Schema({
key3: {type: String, default: '**Value of Key1**'},
key4: {type: String}
})
Here I have two schemas one is a parent schema and another one is child schema, I want to set Key1 value as a default value of Key3. Key1 value is a dynamic value that will be entered by the user.
Thanks in advance.
You can try using Mongoose population.
const ParentSchema = new Schema({
key1: {type: String, required: true},
key2: {type: String, required: true}
})
const ChildSchema = new Schema({
key3: { type: Schema.Types.ObjectId, ref: 'ParentSchema' }
key4: {type: String}
})
Then, you can populate ChildSchema like this:
ChildSchema.
findById(someId).
populate('key3', 'key1').
exec(errorHandlingCb);
For detail implementation see here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.