Mongoose schema virtual attribute always returns undefined

Issue

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?

Solution

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

Answered By – Mohammad Yaser Ahmadi

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.