简体   繁体   中英

How to set default value in mongoose Schema

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.

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.

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM