1

Is there a way to let one field take value of two other fields merged as default. I have a user schema as follows:

const UserSchema = mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },});

I want to add a third field called fullName that defaults to merging firstName + lastName Is that possible in mongoose?

Mohamed Daher
  • 609
  • 1
  • 10
  • 23

2 Answers2

2

try this :


 fullName:{
    type:String,
    required:true,
    default: function(){
      return this.firstName + " " + this.lastName
  }}
  

on doc update :

yourSchema.pre("updateOne", function (next) {

  this.set({ fullName: this.get("firstName") + " " + this.get("lastName")  });

  next();
});

aasem shoshari
  • 190
  • 2
  • 14
  • this works if firstName and lastName are available on creation. but will not work for updates. Thank you https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field – Mohamed Daher Sep 27 '22 at 12:09
  • for updates you need to use pre update/updateOne hook, i edited my answer check it up – aasem shoshari Sep 28 '22 at 11:42
  • nice one i didnt know you have access to the document in the pre update but i see how you used get and set for that. thx – Mohamed Daher Sep 29 '22 at 12:16
1

I solved this using Virtual Setters (Virtuals) as documented by Mongoose

Make sure to add this to your Schema to include virtuals when you convert a document to JSON

const opts = { toJSON: { virtuals: true } };
Mohamed Daher
  • 609
  • 1
  • 10
  • 23