Reputation: 568
For example, I have a schema as below.
const packSchema = new mongoose.Schema({
company: [
name: {type: String},
realName: {type: String, default: ''}
]
})
So I can save a JSON data as below.
[{
"name": "abc",
"realName": "efg"
}]
But when the data doesn't have realName, I want that realName gets data from his own name.
For example, I request this array from ajax call,
[{
"name": "KA"
},
{
"name": "MC"
}]
when I save this object, the result in mongoDB is as below.
[{
"name": "KA",
"realName": "KA"
},
{
"name": "MC",
"realName": "MC"
}]
I think the solution using 'set' option in schema.
function duplicate(){
}
const packSchema = new mongoose.Schema({
company: [
name: {type: String},
realName: {type: String, set: duplicate}
]
})
But I don't know how it can get 'name' data from his own element of array.
Should I use 'for' loop this? or is there other solution?
Thank you for reading it.
Upvotes: 2
Views: 5051
Reputation: 11
Convert company into sub schema and use a pre save hook to update realname
const companySchema = mongoose.Schema({
name: String,
realName: String
})
companySchema.pre('save',function(next) {
if(!this.realName)
this.realName = this.name
next();
})
const packSchema = mongoose.Schema({
company: [companySchema]
})
const Pack = mongoose.model('Pack', packSchema);
Upvotes: 0
Reputation: 50974
The this
inside of your function will get bound to the object which you're creating. As a result, you'll be able to use:
function duplicate(v){
return v === undefined ? this.name : v;
}
Above, if the value for realName
(ie: v
) is undefined, then you'll return this.name
, which is the name
of the object you're inserting/creating. Otherwise, if realName
is already set, it will use that value.
Upvotes: 2