lal_bosdi
lal_bosdi

Reputation: 173

How to concat two fields in mongoosejs resultset

I am querying a collection for a set of documents, but in the result-set i want only 2 fields concatenated with a space. How do i achieve this with mongoosejs in node/express env?

Upvotes: 1

Views: 4149

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59773

Concatenating values is best handled on the client generally speaking unless you are using the aggregation framework.

The easiest is to use use Mongoose virtuals, or you could just do the necessary concatenation on the client in your Node.JS JavaScript code as needed. (To find the specific documentation, go to this page and search for "virtuals").

The example on that web page is essentially what you want:

var personSchema = new Schema({
  name: {
    first: String,
    last: String
  }
});

// compile our model
var Person = mongoose.model('Person', personSchema);

// create a document
var bad = new Person({
    name: { first: 'Walter', last: 'White' }
});

Then, add a virtual:

personSchema.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});

You can limit the results as well by selecting only the fields necessary to perform the concatenation (which is specified by using a space delimited list of the fields you want returned from the database):

Person.find({last: 'White'}, 'first last').exec(/* callback *);

Upvotes: 3

Related Questions