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

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

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

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 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