Mongodb virtual property question?

When we set data with virtual property in mongodb, Is data is actually store in database.
for e.g:

userSchema.virtual('password').set(function (password) {
    console.log("This in set function: ", this);
    this.password = password
    this.salt = this.makeSalt()
    this.hashed_password = this.encryptPassword(password)
}).get(function () {
    console.log("This in get function: ", this)
    return this._password
})

Here I set password field virtually, Is password is actually store in db with password field and why we return password with prefix of underscore in get method?

Hello!

No, virtuals are not stored in the database, that’s the idea :slight_smile:.

Without the entire userSchema it’s hard to know. Usually, properties prefixed with an underscore are meant to denote private properties.

Also, in the code you provide, there’s already a property called password (this.password) defined, which will cause problems. For instance:

const user = new User({ password: '' });

// Which property is this referring to?
// The virtual one or the one defined in the Schema?
user.password = 'new password';

I don’t have password property in actual schema, I have only salt or hash_password property in schema.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.