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

mongodb, mongoose, node.js

Solution

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

Problem

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.

Original source