Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a field in a Mongoose Schema that is a reference to other fields in the same document

So that if the original fields are modified, the copied field changes too.

Pseudo-code example :

userSchema = {
    firstName: {type: String},
    lastName: {type: String},
    displayName: firstName + ' ' + lastName
}

Is something like this possible ?

EDIT: I need to make request based on that field, so I can't just concat the fields when i retrieve them.

like image 908
gsaynac Avatar asked Nov 21 '14 12:11

gsaynac


1 Answers

You can use the hooks http://mongoosejs.com/docs/middleware.html

userSchema = {
    firstName: {type: String},
    lastName: {type: String},
    displayName: {type: String}
}

userSchema.pre('save', function(next) {
    this.displayName = this.username+' '+this.lastName;
    next();
});
like image 79
Barno Avatar answered Sep 28 '22 18:09

Barno