Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda