Mohamed Daher
Mohamed Daher

Reputation: 709

mongoose set a default field to take value of 2 other fields

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?

Upvotes: 2

Views: 1224

Answers (2)

aasem shoshari
aasem shoshari

Reputation: 200

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

Upvotes: 3

Mohamed Daher
Mohamed Daher

Reputation: 709

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

Upvotes: 1

Related Questions