Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
How do I include a virtual field in API response using Mongoose?

How do I include a virtual field in a JSON response

const ItemSchema = mongoose.Schema({
  name: String,
  time: { type: Date, default: Date.now }
});

ItemSchema.virtual('timeleft').get(function() {
  this.timeleft = 24
 
  var currentTime = moment(); 
  var timeStored = moment.utc(this.time).local().format(); 
  this.timeleft -= currentTime.diff(timeStored, 'h');

  
});

API call

app.get('/getAllItems', function(req, res, next) {
   Item.find({}, function(err, items) {
     res.json(items);
   });
});

So technically the response won't include virtual timeleft field. Am I missing something?

[
 {
   name: "nike",
   time: "21/2/22"

  },

  {
   name: "adidas",
   time: "21/2/22"

  },
]
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

// use Schema like this        
const ItemSchema = new Schema({
    name: String,
    time: { type: Date, default: Date.now }
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

ItemSchema.virtual('timeleft').get(function() {
    // this.timeleft = 24
    var currentTime = moment();
    var timeStored = moment.utc(this.time).local().format();
    console.log(" ====== 000 ======== ", currentTime.diff(timeStored, 'h'))
    return this.timeleft = currentTime.diff(timeStored, 'h');
});

const Item = mongoose.model('Item', ItemSchema);

new Item({
    name: 'Axl'
}).save((err, result) => { 
    console.log("=== err ", err, "=== result ", result)
});

Item.find({}, function(err, items) {
    console.log("=========", items)
});
over 4 years ago · Santiago Trujillo Report

0

According to Mongoose docs Mongoose virtuals are not stored in MongoDB, which means you can't query based on Mongoose virtuals.

// Will **not** find any results, because `domain` is not stored in
// MongoDB.
const doc = await User.findOne({ domain: 'gmail.com' });
doc; // undefined

If you want to query by a computed property, you should set the property using a custom setter or pre save middleware.

over 4 years ago · Santiago Trujillo Report

0

Modify your schema as shown below:

const ItemSchema = mongoose.Schema({
    name: String,
    time: { type: Date, default: Date.now },
    toObject: { virtuals: true },  // <-- These properties will configure
    toJSON: { virtuals: true }     //     model to include virtuals
});

Modify your API call as follows:

app.get('/getAllItems', function(req, res, next) {
    Item.find({}, function(err, items) {
        res.json(items.toObject());  // <-- use .toObject() or .toJSON()
    });
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!