0

I have Customer schema:

    var CustomerSchema = new mongoose.Schema({
      name: { type: String, required: true },
      lastname: { type: String, required: true },
      comment: { type: String }
    }, {
     toJSON: { virtuals: true },
     toObject: { virtuals: true }
    });

const Customer = mongoose.model('Customer', CustomerSchema);

I want to add fullname field that return name + lastname.

But the fullname should not return by default only when specify the field, something like populate function does.

for example:

const c = Customer.find().populate('fullname'); // c.fullname

How to do that with mongoose?

** Edit ** I try to do that with virtual:

CustomerSchema.virtual('fullname').get(() => {
      return 'some';
});

But I get the error:

If you are populating a virtual, you must set the localField and foreignField
Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • Checkout this question which has [similar issue](https://stackoverflow.com/questions/55982945/mongoose-populate-virtual-field-with-a-getter-function-is-not-working) – invider Nov 16 '19 at 13:11
  • I did, but I don't need localField or foreignField. just need a function – Jon Sud Nov 16 '19 at 13:14
  • [This issue](https://github.com/Automattic/mongoose/issues/4354) was solved by setting `toObject : {virtuals:true}, toJSON : {virtuals : true}` for `CustomerSchema` – invider Nov 16 '19 at 13:17
  • I did virtuals, but same error message. what else can I do? – Jon Sud Nov 16 '19 at 13:19
  • This is weird. To me, everythng looks as per mongoose documentation and should work. Try opening an issue on [mongoose github repo](https://github.com/Automattic/mongoose/issues) – invider Nov 16 '19 at 13:23
  • Maybe another way to do that? – Jon Sud Nov 16 '19 at 14:24
  • Extend the mongoose.Schema object to suit your need? Create a new object that inherits everything from mongoose schema and add a new function – invider Nov 16 '19 at 17:05

0 Answers0