Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

306
Vistas
Mongoose schema virtual attribute always returns undefined

I was trying to use mongoose schema virtual functions to implement flags, But I could not make them work The mongoose database is hosted on mongodb altas. I have tried deleting the whole collection and staring again.

Here is a simplified example:

Let us say I have a basic User Schema:

const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
  name: String,
  email: String
}, {toObject: {virtuals: true, getters: true}})

UserSchema.virtual('status').get(() => {
   return this.name
})

const User = mongoose.model('User', UserSchema)

module.exports = {
    User,
    UserSchema
}

In app.js I have the following:

const mongoose = require("mongoose");
const express = require("express");
const {User} = require("./models/User")
const app = express();

app.use(express.urlencoded({extended: true}));
app.use(express.json());

mongoose.connect(process.env.DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

User.findById("600ae8001931ad49eae40c03", (err, doc) => {
    console.log(doc.status)
})

const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`server at http://localhost:${port}`);
});

I made sure the id exists, but the result is always undefined. What am I doing wrong here?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

based on mongoose documentation

Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work

so you can not use arrow function in get, do like this :

UserSchema.virtual('status').get(function() {
  return this.name
})
over 4 years ago · Santiago Trujillo Denunciar

0

It's because of how you are declaring your function being passed to get. The way you are doing it is changing the this reference.

UserSchema.virtual('status').get(function() {
  return this.name
})

The above would maintain it

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda