Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
kannavkm Avatar asked May 06 '26 02:05

kannavkm


1 Answers

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
})
like image 64
Mohammad Yaser Ahmadi Avatar answered May 08 '26 17:05

Mohammad Yaser Ahmadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!