Reputation: 113
I am using Mongoose and my model is like-
{
first_name:{
type:String
},
lastName:{
type:String
}
name:{
type:String
}
}
I want whenever i create object with firstName and lastName , name field should be set automatically to firstName+" "+ lastName.
can i use something like we do in Java as-
name = this.firstName+this.lastName
Thanks in advance.
Upvotes: 0
Views: 47
Reputation: 847
I would personally prefer using a virtual for fullname.
var PersonSchema = new Schema({
name: {
first: String
, last: String
}
});
PersonSchema
.virtual('name.full')
.get(function () {
return this.name.first + ' ' + this.name.last;
});
Upvotes: 0
Reputation: 48376
Try it with pre
method
schema.pre('save', function (next) {
this.name = this.lastName + this.firstName;
next();
});
var Person = mongoose.model('Person', schema);
function saveData() {
var p = new Person({
lastName: 'DD',
firstName: 'ss'
});
p.save(function(err, obj) {
console.log(obj);
});
}
And result
{ __v: 0,
name: 'DDss',
lastName: 'DD',
firstName: 'ss',
_id: 56af4489b81a1f2903a13608 }
Upvotes: 1