Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Virtual fields toJSON does not work #5473

Closed
akaNightmare opened this issue Jul 15, 2017 · 4 comments
Closed

Virtual fields toJSON does not work #5473

akaNightmare opened this issue Jul 15, 2017 · 4 comments
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@akaNightmare
Copy link

akaNightmare commented Jul 15, 2017

Do you want to request a feature or report a bug?
Bug.

What is the current behavior?

const schema =  new mongoose.Schema({
   some_field: Number,
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true },
})
schema.virtual('test.a', function() {
    return 1;
});
schema.virtual('test.b', function() {
    return 2;
})

///
console.log(model.toJSON()); // don't see test object
{
    some_field: 1
}

What is the expected behavior?

{
    some_field: 1,
    test: {a:1,b:1}
}

but when model.test.a -> works, toJSON -> not
Please mention your node.js, mongoose and MongoDB version.
Mongoose: 4.11.3
NodeJS: 7.6.0

@TrejGun
Copy link
Contributor

TrejGun commented Jul 16, 2017

schema.virtual("x")
.get(function getX() {
	return this.test.x;
})
.set(function setX(x) {
	this.test.x = x;
});

@vkarpov15
Copy link
Collaborator

Confirmed, thanks for the detailed repro script. Will fix ASAP.

const mongoose = require('mongoose');

const schema =  new mongoose.Schema({
   some_field: Number,
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true },
})
schema.virtual('test.a', function() {
    return 1;
});
schema.virtual('test.b', function() {
    return 2;
})

const Model = mongoose.model('Test', schema);

///
console.log((new Model()).toJSON()); // don't see test object

@sayantan300
Copy link

@vkarpov15 u said 4 yrs ago that it will be fixed asap, but why is the bug still there?

@vkarpov15
Copy link
Collaborator

@sayantan300 please open a new issue and follow the issue template. This issue has been fixed for years and we have the tests to prove it.

@Automattic Automattic locked as resolved and limited conversation to collaborators Mar 31, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

No branches or pull requests

4 participants